我有一个对象数组:
[{ bags:10, pouch:small, weight:100, quantity:1 },
{ bags:101, pouch:large, weight:1001, quantity:11 }]
如何将该数组分成如下所示的多个对象?
small = { bags:10,weight:100,quantity:1 }
large = { bags:101,weight:1001,quantity:11 }
最佳答案
确实可以,但我不推荐它!
var data = [{ bags: 10, pouch: 'small', weight: 100, quantity: 1 }, { bags: 101, pouch: 'large', weight: 1001, quantity: 11 }],
object = data.forEach(function (a) {
window[a.pouch] = { bags: a.bags, weight: a.weight, quantity: a.quantity };
});
document.write('<pre>' + JSON.stringify(small, 0, 4) + '</pre>');
document.write('<pre>' + JSON.stringify(large, 0, 4) + '</pre>');
使用对象更好的解决方案
您可以首先构建一个使用 pouch
值作为属性的对象,然后将它们分配给所需的变量。
var data = [{ bags: 10, pouch: 'small', weight: 100, quantity: 1 }, { bags: 101, pouch: 'large', weight: 1001, quantity: 11 }],
object = data.reduce(function (r, a) {
r[a.pouch] = { bags: a.bags, weight: a.weight, quantity: a.quantity };
return r;
}, {});
document.write('<pre>' + JSON.stringify(object, 0, 4) + '</pre>');
var small = object.small,
large = object.large;
document.write('<pre>' + JSON.stringify(small, 0, 4) + '</pre>');
document.write('<pre>' + JSON.stringify(large, 0, 4) + '</pre>');
关于javascript - 将对象数组转换为不同的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34767791/