将json的每个对象的值集推送到不同的数组中

时间:2015-03-04 17:17:38

标签: javascript underscore.js

目前我有以下代码,一个JSON文件,并且使用下划线我将每个外观的产品ID推送到一个数组中,我想要做的是将每个外观的产品ID推送到他们自己的数组中,所以我会productArray1productArray2productArray3等。我怎么能适应这个?

JSON

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

JS(下划线)

var productArray = []
_.each(looks, function(look) {
  _.each(look.products, function(product) {
    productArray.push(product.replace(/_.*/, ''))
  })
})

3 个答案:

答案 0 :(得分:1)

我可能会误解,但你是在问如何创建一个数组数组?

var productArrays = [];
_.each(looks, function(look) {
  var productArray = [];
  _.each(look.products, function(product) {
    productArray.push(product.replace(/_.*/, ''))
  })
  productArrays.push(productArray);
});

例如:http://jsfiddle.net/bvaughn/acam2rzo/

此代码将生成如下的2D数组:

[
  ["hbeu50271385"1: "hbeu50274296"2: "hbeu50272359"3: "hbeu50272802"],
  ["hbeu50274106"1: "hbeu50273647"2: "hbeu50274754"3: "hbeu50274063"4: "hbeu50274911"5: "hbeu50274106"6: "hbeu50240022"7: "hbeu50271944"length],
  ["hbeu50272935"1: "hbeu50274426"2: "hbeu50271624"3: "hbeu50274762"4: "hbeu50275366"5: "hbeu50274433"6: "hbeu50262002"7: "hbeu50272364"8: "hbeu50272359"]
];

答案 1 :(得分:1)

让我们构建一个[name, products]对的列表,然后将该列表传递给_.object,以输出一个具有productArrayn作为键的对象和所需的产品数组作为值:

var res = _.chain(looks).
    map(function(look) {
        return [
            "productArray" + look.id.substr(4),
            _.map(look.products, function(product) {
                return product.replace(/_.*/, '');
            })
        ];
    }).
    object().
    value();

会输出

productArray1: ["hbeu50271385", "hbeu50274296", ...],
productArray2: ["hbeu50274106", "hbeu50273647", ...],
productArray3: ["hbeu50272935", "hbeu50274426", ...],
....

演示http://jsfiddle.net/nikoshr/fkmtksz5/

答案 2 :(得分:0)

这样的事情可行,productArrays将包含您的每个产品数组,使用其ID作为键,例如:productArrays.look1包含所有look1的产品。

var productArrays = {};

_.each(looks, function (look) {
  productArrays[look.id] = [];

  _.each(look.products, function (product) {
    productArrays[look.id].push(product.replace(/_.*/, ''));
  });

});