Reputation: 1460
I have an array of objetcs whith each object containing arrays.I need to manipulate it so that element within the inner arrays are appended if different or kept as single if the same; basically are grouped by type
. It's a bit hard to explain so I give you an example.
Here is the array I have:
let array1 = [{
1: [{
id: "aaaa",
name: 'name1',
type: 1
}],
2: [{
id: 'bbbb',
name: 'name2',
type: 2
}],
3: [{
id: "ccc",
name: 'name3',
type: 3
}]
},
{1: [{
id: "aaaa",
name: 'name1',
type: 1
}],
2: [{
id: 'bbbb',
name: 'name2',
type: 2
}],
3: [{
id: "dddd",
name: 'name4',
type: 3
}],
};
And I would like to get something like the following object:
let result = {
1: [
{
id: "aaaa",
name: 'name1',
type: 1
}],
2: [{
id: 'bbbb',
name: 'name2',
type: 2
}],
3: [{
id: "cccc",
name: 'name3',
type: 3
},
{
id: "dddd",
name: 'name4',
type: 3
}
]
}
what would be the most efficient way to do this (possibly using lodash)? I have tried something with foreach and assign but I alwaays end up overriding the inner array... Thank you for help!
Upvotes: 0
Views: 456
Reputation: 5577
You can use _.mergeWith to pass comparison function:
var result = array1.shift();
_.mergeWith(result, ...array1, function(a, b) {
return _.isEqual(a, b) ? a : _.concat(a, b);
});
console.log(result);
Upvotes: 1