Accessing object value in array from json in route node
How do I access the value of an object in an array? In particular, the meaning of "namecase"? I have an ejs view loop in an array so that it can display all my object values. I am 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>
<% }
+3
source to share
1 answer
What you want is concat item.projects
, not namecase
how you are doing. Also, after you are in works
a projects
child object, you will want to loop through the projects and then execute them like this:
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
});
});
However, only projects are returned:
[ { 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: '/' } ]
+1
source to share