Reputation: 4944
Lets say I have the following array of objects:
myArray = [
{name: 'First', parent: 1, delta: 2},
{name: 'Second', parent: 1, delta: 1},
{name: 'Third', parent: 2, delta: 1}
];
I would like to convert this array to an object, with keys for the parent, and values of the objects. e.g.:
result = {
1: [
{name: 'First', parent: 1, delta: 2},
{name: 'Second', parent: 1, delta: 1}
],
2: [
{name: 'Third', parent: 2, delta: 1}
]
}
I can do this using a forEach
, or nested loops, but am wondering if there is a way using ES6 syntax to do this a bit more concise/inline, which would allow me to do things like sort on delta
, etc.
Upvotes: 1
Views: 69
Reputation: 1776
const result = myArray.reduce((result, el) => {
if (result[el.parent]) result[el.parent].push(el);
else result[el.parent] = [el];
return result;
}, {});
Upvotes: 1
Reputation: 4184
You can use reduce to achieve this
var myArray = [
{name: 'First', parent: 1, delta: 2},
{name: 'Second', parent: 1, delta: 1},
{name: 'Third', parent: 2, delta: 1}
];
var result = myArray.reduce((o,d) =>
(
o[d.parent] = (o[d.parent] || []).concat(d)
, o
)
, {})
console.log(result)
Upvotes: 1
Reputation: 30739
You can use Array.reduce()
for that:
let myArray = [{
name: 'First',
parent: 1,
delta: 2
},
{
name: 'Second',
parent: 1,
delta: 1
},
{
name: 'Third',
parent: 2,
delta: 1
}
];
var res = myArray.reduce((acc, item) => {
if (acc[item.parent]) {
acc[item.parent].push(item);
} else {
acc[item.parent] = [item];
}
return acc;
}, {});
console.log(res);
Upvotes: 2
Reputation: 6233
var myArray = [
{name: 'First', parent: 1, delta: 2},
{name: 'Second', parent: 1, delta: 1},
{name: 'Third', parent: 2, delta: 1}
];
console.log(myArray.reduce((acc, val)=>({...acc, [val.parent]: (acc[val.parent] || []).concat(val)}), {}))
Upvotes: 1