从节点路由中的json访问数组中的对象值

时间:2014-11-29 01:34:41

标签: javascript node.js express ejs embedded-javascript

如何访问数组中的对象值?具体“名称”值?我在数组中循环了一个ejs视图,以便它可以显示我的所有对象值。我通过路线传递数据。

//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 个答案:

答案 0 :(得分:1)

你想要的是连结item.projects,而不是你正在做的namecase密钥。此外,一旦你进入works对象的projects子对象,你就会想要遍历项目,然后然后将它们连接起来,如下所示:

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
  });
});

这样做只会返回项目:

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