Reputation: 131
I'm trying to render html using jade, and I want to iterate over an array of objects. For each object, I want to print all of the values on one line in an li.
Here's my backend code using express:
router.get('/', function(req, res, next) {
fs.readFile('./contacts.json', function(err, data){
if (err) return res.status(400).send(err);
var contactArr = JSON.parse(data);
res.render('contacts', {contactArr : contactArr});
});
});
-- contactArr is an array of objects in JSON format like this:
[{"name":"Jennifer","email":"[email protected]"},{"name":"Mike","email":"[email protected]"}]
And here is the front end jade code that I'm trying to make work:
extends layout
block content
ul
each contact in #{contactArr}
li #{contact[0].name}
I've read all about iterating with jade here: http://jade-lang.com/reference/iteration/ , but I can't seem to get the syntax right for iterating over an array of objects to get out all the values.
UPDATE: I realized that part of the problem was that I was attempt to reference the contactArr incorrectly. The #{ } syntax was unnecessary. Just "contactArr" in the jade code gives me access to the array. However, I am still struggling to figure out how to iterate over the keys in each object in the array.
Upvotes: 0
Views: 2842
Reputation:
Just try this code:
ul
each contact in contactArr
li
each value, key in contact
span= key + ': ' + value + ' '
In the snippet above, key is the name of the field. So, for your input it should render something like this:
Upvotes: 2
Reputation: 331
The issue seems to be that you are indexing into the individual contact when you don't need to be: contact[0].name
.
In the Jade each
loop, you're pulling out each individual object as contact
already, so you should be able to just use contact.name
.
Also, the #{contactArr}
syntax may be causing a problem - within the each
loop, you should just be able to use contactArr
.
Upvotes: 1