3

How can access an object value in an array? Specifically "namecase" value? I have a ejs view looping in the array so that it can display all my object values. I'm passing data through routes.

//data.json
{
  "works": [{
    "company" : "Company 1",
    "projects": [{
      "namecase":"Projectname 1",
      "desc":"This is a project with fairies.",
      "img" : "/images/placeholder.jpg",
      "url" : "/" 
      },
      {
      "namecase":"Projectname 2",
      "desc":"This is a project with monsters.",
      "img" : "/images/placeholder.jpg",
      "url" : "/" 
      }]
      }

  ]

}

//index.js route

var appdata = require('../data.json');

router.get('/work', function(req, res) {
    var myProjects = [];
    appdata.works.forEach ( function (item){
//this is where I pull object from json
        myProjects = myProjects.concat(item.projects["namecase"]);
    });
  res.render('work', { 
    title: 'Work',
    projects: myProjects
  });
});

///ejs

    <% if (projects.length > 0) { %>
    <% for (i=0; i<projects.length; i++) { %>

    <span><%= projects["namecase"] %></span>


    <% }

1 Answer 1

1

What you want is to concat item.projects, not the namecase key as you're doing. Also, once you're in the works object's projects child object, you'll want to loop through the projects and then concat them, like so:

router.get('/work', function(req, res) {
  var myProjects = [];
  appdata.works.forEach(function(work) {
    // Loop through each project to prevent undefined indices from being concatenated
    work.projects.forEach(function(project) {
      myProjects = myProjects.concat(project);
    });
  });
  res.render('work', { 
    title: 'Work',
    projects: myProjects
  });
});

Doing so will return just the projects:

[ { namecase: 'Projectname 1',
    desc: 'This is a project with fairies.',
    img: '/images/placeholder.jpg',
    url: '/' },
  { namecase: 'Projectname 2',
    desc: 'This is a project with monsters.',
    img: '/images/placeholder.jpg',
    url: '/' } ]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.