gpt4 book ai didi

javascript - 通过对对象数组进行排序动态创建多个数组

转载 作者:行者123 更新时间:2023-11-28 13:16:03 25 4
gpt4 key购买 nike

给定以下对象数组:

var fruits = [
{ type: "banana", number: 20 },
{ type: "apple", number: 2 },
{ type: "pineapple", number: 40 },
{ type: "pineapple", number: 32 },
{ type: "banana", number: 80 },
{ type: "pineapple", number: 24 },
{ type: "apple", number: 64 },
{ type: "apple", number: 12 }
]

如何按类型键对其进行排序,并为每种类型动态创建一个新的对象数组?要获得这样的东西:

// new array of bananas:
[
{ type: "banana", number: 20 },
{ type: "banana", number: 80 }
]

// new array of apples:
[
{ type: "apple", number: 2 },
{ type: "apple", number: 64 },
{ type: "apple", number: 12 }
]

// new array of pineapples:
[
{ type: "pineapple", number: 40 },
{ type: "pineapple", number: 32 },
{ type: "pineapple", number: 24 }
]

最佳答案

这是我的解决方案,循环遍历项目,将其放入具有匹配键的列表中

    var fruits = [
{ type: "banana", number: 20 },
{ type: "apple", number: 2 },
{ type: "pineapple", number: 40 },
{ type: "pineapple", number: 32 },
{ type: "banana", number: 80 },
{ type: "pineapple", number: 24 },
{ type: "apple", number: 64 },
{ type: "apple", number: 12 }
];

var data = {};


fruits.forEach(function(fruit){
if (data[fruit.type]) {
data[fruit.type].push(fruit);
} else {
data[fruit.type] = [fruit];
}
});

console.log(data);

关于javascript - 通过对对象数组进行排序动态创建多个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38032347/

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