자동차에 대한 정보가있는 개체가 여러 개 있습니다. 나는 그룹화하고 싶다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' }
]
]
이것은 내 솔루션이지만 감소 또는 ...를 기반 으로이 결과에 대한 방법을 원합니다 if
.forEach
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);
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다