[英]how to create dynamic multi-dimensional array of objects with in javascript
I have an array of objects that has information about cars.我有一组包含汽车信息的对象。 I want to grouping on
categoryId
我想对
categoryId
进行分组
var car = [
{ category: 1, model: "bmw" },
{ category: 1, model: "benz" },
{ category: 1, model: 'ford' }
{ category: 2, model: "kia" },
{ category: 2, model: "fiat" },
{ category: 3, model: "mg" },
];
I want this result我想要这个结果
[
[
{ category: 1, model: 'bmw' },
{ category: 1, model: 'benz' },
{ category: 1, model: 'ford' }
],
[
{ category: 2, model: 'kia' },
{ category: 2, model: 'fiat' }
],
[
{ category: 3, model: 'mg' }
]
]
this is my solution but I want a way for this result based on reduce or... I dont want to use if
in forEach
这是我的解决方案,但我想要一种基于 reduce 的结果的方法,或者......我不想在
forEach
中使用if
let groupedCars = [];
cars.forEach((car) => {
if (!groupedCars[car.category]) {
groupedCars[car.category] = [];
}
groupedCars[car.category].push(car);
});
Solution using Array.prototype.reduce()
method.使用
Array.prototype.reduce()
方法的解决方案。 Traverse the array and group it by category using reduce and at last, use Object.values()
to get the result.使用reduce遍历数组并按类别分组,最后使用
Object.values()
得到结果。
const car = [ { category: 1, model: 'bmw' }, { category: 1, model: 'benz' }, { category: 1, model: 'ford' }, { category: 2, model: 'kia' }, { category: 2, model: 'fiat' }, { category: 3, model: 'mg' }, ]; const ret = Object.values( car.reduce((prev, c) => { const p = prev; const key = c.category; p[key] = p[key]?? []; p[key].push({...c }); return p; }, {}) ); console.log(ret);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.