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'
}
]
}