简体   繁体   English

如何在 javascript 中创建动态多维对象数组

[英]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);

Not clear what you mean by result based on ES6 .不清楚您所说的基于 ES6 的结果是什么意思。 But, you could try using reduce method.但是,您可以尝试使用reduce方法。

NOTE : Javascript arrays start with index 0 so, you might need to add some logic in your code to fix that注意: Javascript arrays 以索引0开头,因此,您可能需要在代码中添加一些逻辑来修复该问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM