用于项对象的主干方法

Backbone where method for item object

本文关键字:方法 对象 用于      更新时间:2023-09-26

下面是JSON数据示例

"items": [{
                "id": "18",
                "attributes": [{
                    "identifier": "Style",
                    "value": "peacock"
                }, {
                    "identifier": "Size",
                    "value": "L"
                }]
            },
            {
                "id": "300438",
                "attributes": [{
                    "identifier": "Style",
                    "value": "peacock"
                }, {
                    "identifier": "Size",
                    "value": "M"
                }]
            }]

我需要得到的项目id,其中Style = peacock和Size = L。我如何使用骨干网做到这一点?

我做了一个像

这样的集合
var itemsCollection = new IEA.Collection(itemsData)

underscore.js不支持对嵌套对象进行过滤,您可以在filter和where函数之间组合使用

filteredItems = itemsCollection.filter(function(item) {
  return _.where(item.get("attributes"), {
      "identifier": "Style",
      "value": "peacock"
    }).length > 0 &&
    _.where(item.get("attributes"), {
      "identifier": "Size",
      "value": "M"
    }).length > 0;
});

可选。我通过创建新的数组并在其中存储所需的值来简化JSON。然后使用backbone where方法返回id。

 productData.items.forEach(function(item, index) {
                    var data = {'id': item.id};
                    item.attributes.forEach(function(attribute) {
                        data[attribute.identifier] = attribute.value
                    });
                    productVariants.push(data);
                });

var itemsCollection = new backbone.Collection(productvariables);