Merge N Object From Array Into One Array Based On Id
I'm trying to merge n objects from an array of objects listed below. I tried to use reduce method, but I can't understand what I'm doing wrong, still new to advance js methods. c
Solution 1:
In your code, if you already have a r[id]
, you didn't assign the rest values. So change it like this:
const result = Object.values(
array.reduce((r, { data }) => {
Object.entries(data).forEach(([id, { ...el }]) => {
r[id] = {
...r[id], // this is the point
id,
...el
};
});
return r;
}, {})
);
Solution 2:
Here's one way that combines map, reduce, and entries Array methods.
const array = [
{
data: {
'1': {
foo: 'bar',
test: true
},
'4': {
foo: 'boor'
}
}
},
{
data: {
'1': {
x: 'o',
test2: false
}
}
}
];
const merged = array.map(el => el.data).reduce((acc, el) => {
Object.entries(el).forEach(([key, obj]) => {
if(!acc[key]) acc[key] = {};
acc[key] = { ...acc[key], ...obj };
});
return acc;
}, {});
const mergedArr = Object.entries(merged).reduce((acc, [key, obj]) => {
acc.push({
id: key,
...obj
});
return acc;
}, []);
console.log(mergedArr);
Solution 3:
var array = [
{
data: {
'1': {
foo: 'bar',
test: true
},
'4': {
foo: 'boor'
}
}
},
{
data: {
'1': {
x: 'o',
test2: false
}
}
}
];
var mergedObject = [];
array.forEach(data =>Object.keys(data.data).forEach(id => mergedObject = {
...mergedObject,
[id]: {
...mergedObject[id],
...data.data[id]
}
}))
console.log("mergedObject="+JSON.stringify(mergedObject));
var mergedArray = Object.keys(mergedObject).map(id => ({
id,
...mergedObject[id]
}))
console.log("mergedArray="+JSON.stringify(mergedArray));
Solution 4:
Assuming an array of objects with ids, I've done this often and it's just two steps.
- group by id to create an index. (
_.groupBy
is from underscorejs but a common op) - pluck the values from the index.
Object.vals(_.groupBy(arr, function(item){
return item.id;
}))
From an FP perspective, do one thing at a time to get the data into a shape that the next step can readily use. Don't try to do two things at once.
Post a Comment for "Merge N Object From Array Into One Array Based On Id"