This is similar to the question How can I group an array of complex objects by key but my data is complex and the solution provided did not work.
const cars = [
{
'make': 'audi',
'model': ['r8','r9'],
'year': '2012'
}, {
'make': 'audi',
'model': ['r8','r9'],
'year': '2013'
}, {
'make': 'ford',
'model': ['mustang','mustang lx'],
'year': '2012'
}, {
'make': 'ford',
'model': ['mustang','mustang lp'],
'year': '2015'
}, {
'make': 'kia',
'model': 'optima',
'year': '2012'
},
];
I want to make a new array of car objects that's grouped by make:
{
'audi': [
{
'make': 'audi',
'model': ['r8','r9'],
'year': '2012'
}, {
'make': 'audi',
'model': ['r8','r9'],
'year': '2013'
}
],
'ford': [
{
'make': 'ford',
'model': ['mustang','mustang lx'],
'year': '2012'
}, {
'make': 'ford',
'model': ['mustang','mustang lp'],
'year': '2015'
}
],
'kia': [
{
'make': 'kia',
'model': 'optima',
'year': '2012'
}
]
}
I tried
for (let { domain, ...fields } of items) {
result[domain] = result[domain] || [];
result[domain].push({ ...fields });
}
and
result = items.reduce(function (r, a) {
r[a.domain] = r[a.domain] || [];
r[a.domain].push(a);
return r;
}, Object.create(null));
the output was
{
'audi': [
{
'make': 'audi',
'model': [Array],
'year': '2012'
}, {
'make': 'audi',
'model': [Array],
'year': '2013'
}
],
'ford': [
{
'make': 'ford',
'model': [Array],
'year': '2012'
}, {
'make': 'ford',
'model': [Array],
'year': '2015'
}
],
'kia': [
{
'make': 'kia',
'model': 'optima',
'year': '2012'
}
]
}
CodePudding user response:
You can try this :
let groupBy = (arr, key) => {
return arr.reduce((rv, x) => {
(rv[x[key]] = rv[x[key]] || []).push(x);
return rv;
}, {});
};
let res = groupBy(cars, 'make');
console.log(res);
// Output :
// {
// "audi": [
// {
// "make": "audi",
// "model": [
// "r8",
// "r9"
// ],
// "year": "2012"
// },
// {
// "make": "audi",
// "model": [
// "r8",
// "r9"
// ],
// "year": "2013"
// }
// ],
// "ford": [
// {
// "make": "ford",
// "model": [
// "mustang",
// "mustang lx"
// ],
// "year": "2012"
// },
// {
// "make": "ford",
// "model": [
// "mustang",
// "mustang lp"
// ],
// "year": "2015"
// }
// ],
// "kia": [
// {
// "make": "kia",
// "model": "optima",
// "year": "2012"
// }
// ]
// }
CodePudding user response:
we can use lodash library to do this
const cars = [
{
'make': 'audi',
'model': ['r8','r9'],
'year': '2012'
}, {
'make': 'audi',
'model': ['r8','r9'],
'year': '2013'
}, {
'make': 'ford',
'model': ['mustang','mustang lx'],
'year': '2012'
}, {
'make': 'ford',
'model': ['mustang','mustang lp'],
'year': '2015'
}, {
'make': 'kia',
'model': 'optima',
'year': '2012'
},
];
console.log(_.groupBy(cars, d=> d.make))
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>