仅在下划线循环中显示唯一值

时间:2015-03-05 08:55:58

标签: javascript underscore.js

我使用下划线循环为每个外观显示json文件中的产品ID。我想确保循环中不包含重复的id,我该怎么做?

JS(下划线)

  <% _.each( listItem.products, function( product, index ){ %>                                                                           
          <li class="tab-link productTile tab-<%= index + 1 %>" data-tab-id="<%= index + 1 %>" data-product-pid-thumb="<%= product %>"></li>
    <% }) %>

JSON

looks = [{
        "id": "look1",
        "products": ["hbeu50271385", "hbeu50274296", "hbeu50272359", "hbeu50272802", "hbeu50272802", "hbeu50272802", "hbeu50272802"]
    }, {
        "id": "look2",
        "products": [
            "hbeu50274106", "hbeu50273647", "hbeu50274754", "hbeu50274063", "hbeu50274911", "hbeu50274106", "hbeu50240022", "hbeu50271944"
        ]
    }, {
        "id": "look3",
        "products": [
            "hbeu50272935", "hbeu50274426", "hbeu50271624", "hbeu50274762", "hbeu50275366", "hbeu50274433", "hbeu50262002", "hbeu50272364", "hbeu50272359"
        ]
    }
    .......
]

1 个答案:

答案 0 :(得分:0)

你可以像这样使用_uniq方法:

var looks = [{id:1}, {id:1}, {id:2}];

var uniqProducts = _.uniq(looks, function(l) {
  return l.id;
});

然后在循环中更改为此变量:

 <% _.each( uniqProducts, function( product, index ){ %>                                                                           
  <li class="tab-link productTile tab-<%= index + 1 %>" data-tab-id="<%= index + 1 %>" data-product-pid-thumb="<%= product %>"></li>
 <% }) %>