Search code examples
javascriptnode.jsexpressejsembedded-javascript

Accessing object value in array from json in node route


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>


    <% }

Solution

  • 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: '/' } ]