如何迭代Lodash中的数组中的对象

我正在尝试在HTML模板中使用lodash来获取Node.js中的电子邮件。 我有一个数组与几个对象。 我想遍历每个对象,并列出所有的重复值。 当我使用下面的代码时,我收到一个错误,指出该值是未定义的(例如, ReferenceError: firstName is not defined )。 HTML模板在一个单独的文件中。

任何想法,我在做什么错了?

使用Javascript:

 var template = fs.readFileSync('server/views/email-template.html').toString(); var htmlAll = _.template(template)(orderInfo); 

HTML:

 <% _.forEach(function(firstName) { %><%- firstName %></td><% }); %> <% _.forEach(function(lastName) { %><%- lastName %></td><% }); %> <% _.forEach(function(address) { %><%- address %></td><% });%> <% _.forEach(function(city) { %><%- city %><% }); %>, <% _.forEach(function(state.code) { %><%- state.code %><% }); %> <% _.forEach(function(zip) { %><%- zip %><% }); %> <% _.forEach(function(item) { %><td><%- item %></td><% }); %> <% _.forEach(function(cost) { %><td><%- cost %></td><% }); %> 

阵:

 [ { "firstName": "John", "lastName": "Doe", "address": "123 Broadway", "city": "New York", "state": { "code": "NY", "state": "New York" }, "zip": "10001", }, { "color": "White", "size": "M", "item": "T-Shirt", "cost": 19.99, }, { "color": "Blue", "size": "L", "item": "T-Shirt", "cost": 19.99, } ] 

实际上这里有一些错误。 从模板语法开始,您只是指定要在模板中进行foreach的迭代器,但是我们需要的数据和迭代器如下所示

 _.forEach(users, function(user){ 

你也有单个数组位置的多个对象,所以我也更新了json结构。

小小的更新模板之后,有些财产故意失踪,

 var tmpl = _.template('<ul><% _.forEach(users, function(user) { %><li><%- user.firstName %></li><li><%- user.address %></li><li><%- user.state.code %></li><li><%- user.state.state %></li><ol> <% _.forEach(user.orders, function(order) { %> <li><span><%- order.item %><span> cost is: <span><%- order.cost %><span></li> <% }); %> </ol> <% }); %></ul>'); 

和json的命令数组在同一个对象如下

 var data = { 'users': [ { "firstName": "John", "lastName": "Doe", "address": "123 Broadway", "city": "New York", "state": { "code": "NY", "state": "New York" }, "zip": "10001", "orders": [ { "color": "White", "size": "M", "item": "T-Shirt", "cost": 19.99, }, { "color": "Blue", "size": "L", "item": "Pant", "cost": 19.99, } ] } ] }; 

你可以在JSBIN看到它在这里工作

这是因为你给了你的模板orderInfo[0] 。 而在你的数组中, orderInfo[0]就是这个部分:

 { "firstName": "John", "lastName": "Doe", "address": "123 Broadway", "city": "New York", "state": { "code": "NY", "state": "New York" }, "zip": "10001", } 

所以模板不能迭代丢失的值。