如何在Lodash中遍历数组中的对象

Ken*_*Ken 14 node.js underscore.js 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);
Run Code Online (Sandbox Code Playgroud)

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><% }); %>
Run Code Online (Sandbox Code Playgroud)

阵:

[
  {
    "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,
  }
]
Run Code Online (Sandbox Code Playgroud)

Has*_*sif 14

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

_.forEach(users, function(user){
Run Code Online (Sandbox Code Playgroud)

你在单个数组位置有多个对象,所以我也更新了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>');
Run Code Online (Sandbox Code Playgroud)

和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,
        }
  ]  
  } 
]
};
Run Code Online (Sandbox Code Playgroud)

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


Mag*_*gus 1

这是因为你给了orderInfo[0]你的模板。在你的数组中,orderInfo[0]只有这一部分:

{
    "firstName": "John",
    "lastName": "Doe",
    "address": "123 Broadway",
    "city": "New York",
    "state": {
      "code": "NY",
      "state": "New York"
    },
    "zip": "10001",
}
Run Code Online (Sandbox Code Playgroud)

因此模板无法迭代缺失的值。