gpt4 book ai didi

javascript - 将对象数组转换为不同的对象

转载 作者:行者123 更新时间:2023-11-29 18:01:17 24 4
gpt4 key购买 nike

我有一个对象数组:

[{ 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com