[英]how to create dynamic multi-dimensional array of objects with in javascript
我有一组包含汽车信息的对象。 我想对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" },
];
我想要这个结果
[
[
{ category: 1, model: 'bmw' },
{ category: 1, model: 'benz' },
{ category: 1, model: 'ford' }
],
[
{ category: 2, model: 'kia' },
{ category: 2, model: 'fiat' }
],
[
{ category: 3, model: 'mg' }
]
]
这是我的解决方案,但我想要一种基于 reduce 的结果的方法,或者......我不想在forEach
中使用if
let groupedCars = [];
cars.forEach((car) => {
if (!groupedCars[car.category]) {
groupedCars[car.category] = [];
}
groupedCars[car.category].push(car);
});
使用Array.prototype.reduce()
方法的解决方案。 使用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);
不清楚您所说的基于 ES6 的结果是什么意思。 但是,您可以尝试使用reduce
方法。
注意: Javascript arrays 以索引0
开头,因此,您可能需要在代码中添加一些逻辑来修复该问题
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.