提问人:Butri 提问时间:11/4/2023 最后编辑:Butri 更新时间:11/4/2023 访问量:72
从给定数组创建包含多个对象和数组的新数组
Create a new array of multiple objects and array from a given array
问:
我有以下数组
const CARS =
[
{make: "skoda", model: "kodiaq", color: "light-blue", id: "1002", category: "A"},
{make: "skoda", model: "karoq", color: "green", id: "1008", category: "B"},
{make: "renault", model: "clio", color: "grey", id: "1006", category: "A"},
{make: "renault", model: "kangoo", color: "white", id: "1042", category: "C"},
{make: "mazda", model: "cx3", color: "red", id: "1022", category: "C"},
{make: "mazda", model: "cx30", color: "orange", id: "1106", category: "D"},
{make: "ford", model: "explorer", color: "grey", id: "1162", category: "B"},
{make: "ford", model: "edge", color: "red", id: "1862", category: "A"}
]
我需要创建一个按“category”属性分组的新对象数组,如下所示
const NEW_CARS =
[
{
category: "A",
data:
[
{make: "skoda", model: "kodiaq", color: "light-blue", id: "1002", category: "A"},
{make: "renault", model: "clio", color: "grey", id: "1006", category: "A"},
{make: "ford", model: "edge", color: "red", id: "1862", category: "A"}
]
},
{
category: "B",
data:
[
{make: "skoda", model: "karoq", color: "green", id: "1008", category: "B"},
{make: "ford", model: "explorer", color: "grey", id: "1162", category: "B"},
]
},
{
category: "C",
data:
[
{make: "renault", model: "kangoo", color: "white", id: "1042", category: "C"},
{make: "mazda", model: "cx3", color: "red", id: "1022", category: "C"}
]
},
{
category: "D",
data:
[
{make: "mazda", model: "cx30", color: "orange", id: "1106", category: "D"}
]
}
]
我想我需要从原始数组中提取类别列表并再次循环创建一个新数组。我迷路了,也不确定什么是性能最高的方法,因为我的数组实际上非常大。
答:
2赞
code
11/4/2023
#1
您可以使用 Object.groupBy
然后转换为您想要的表单:
Object.entries(
Object.groupBy(CARS, ({ category }) => category)
).map(([category, data]) => ({ category, data }))
2赞
Keyboard Corporation
11/4/2023
#2
为此,我 CARS 然后有平等。reduce
find
使用条件检查它们的相等性,如果为 TRUE,我需要将其添加到一个称为 existing_category 的数组中。否则,我会将其添加到名为累加器的数组中。
最后,我将返回累加器以查看NEW_CARS执行后的结果。
const CARS = [
{make: "skoda", model: "kodiaq", color: "light-blue", id: "1002", category: "A"},
{make: "skoda", model: "karoq", color: "green", id: "1008", category: "B"},
{make: "renault", model: "clio", color: "grey", id: "1006", category: "A"},
{make: "renault", model: "kangoo", color: "white", id: "1042", category: "C"},
{make: "mazda", model: "cx3", color: "red", id: "1022", category: "C"},
{make: "mazda", model: "cx30", color: "orange", id: "1106", category: "D"},
{make: "ford", model: "explorer", color: "grey", id: "1162", category: "B"},
{make: "ford", model: "edge", color: "red", id: "1862", category: "A"}
];
const NEW_CARS = CARS.reduce((accumulator, car) => {
const exist_category = accumulator.find(category => category.category === car.category)
if (exist_category) {
exist_category.data.push(car)
} else {
accumulator.push({category: car.category,data: [car]})
}
return accumulator;
}, []);
console.log(NEW_CARS);
评论