我有一个对象数组:
[{ 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 }
答案 0 :(得分:3)
它做到了,但我不推荐它!
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>');
&#13;
使用对象更好的解决方案
您可以先使用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>');
&#13;
答案 1 :(得分:1)
所以步骤是:
找到您想要的条目,
为小袋创建一个对象
复制所需的属性
所以:
var array = [{ bags:10,pouch:"small",weight:100,quantity:1},{bags:101,pouch:"large",weight:1001,quantity:11}];
var small = get(array, "small");
var large = get(array, "large");
snippet.log("small = " + JSON.stringify(small));
snippet.log("large = " + JSON.stringify(large));
function get(array, pouch) {
// Find the entry (on newer browsers you could use Array#find, and it
// can be shimmed; I used Array#some here)
var found;
array.some(function(entry) {
if (entry.pouch == pouch) {
found = entry;
return true;
}
});
if (found) {
// Found it, create an object with the properties we want
return {
bags: found.bags,
weight: found.weight,
quantity: found.quantity
};
}
return null;
}
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="//tjcrowder.github.io/simple-snippets-console/snippet.js"></script>