Reputation: 6168
I am recently started using lodash, I want to merge following objects.
{
"1" : [
{
name: "karthick",
age : 25
},
{
name: "arun",
age : 20
}
],
"2" : [
{
name: "varun",
age : 25
},
{
name: "smith",
age : 20
}
]
}
{
"1" : [
{
name: "gautham",
age : 17
},
{
name: "mathan",
age : 19
}
],
"2" : [
{
name: "ashok",
age : 16
},
{
name: "dharani",
age : 20
}
]
}
{
"1" : [
{
name: "karthick",
age : 25
},
{
name: "arun",
age : 20
},
{
name: "gautham",
age : 17
},
{
name: "mathan",
age : 19
}
]
"2" : [
{
name: "varun",
age : 25
},
{
name: "smith",
age : 20
},
{
name: "ashok",
age : 16
},
{
name: "dharani",
age : 20
}
]
}
Any suggestion will be grateful
Upvotes: 1
Views: 433
Reputation: 23382
In the documentation you can read you have to use a customizer function that concats the arrays for you. (https://lodash.com/docs#mergeWith)
This method looks like this:
function customizer(objValue, srcValue) {
if (_.isArray(objValue)) {
return objValue.concat(srcValue);
}
}
Here's it used in your example:
https://jsfiddle.net/82koarwq/
If you want to better understand what's happening inside the merge method:
Merge takes the first object that it is passed as a base. It then loops through all the keys in the other objects it is passed (in order of arguments). It does two things:
By using mergeWith, you have the opportunity to overwrite this behavior. You can pass a method that is used to deal with the second case. If you want to fall back on the default merge behavior, you'll have to make your method return undefined.
Upvotes: 1
Reputation: 68393
Try this updated fiddle
var output = {};
var firstObjKeys = Object.keys(firstObj);
var secondObjKeys = Object.keys(secondObj).filter(function(val){
return firstObjKeys.indexOf(val) == -1;
});
var allKeys = firstObjKeys.concat(secondObjKeys);
allKeys.forEach(function(val){
var firstArr = firstObj[val] || [];
var secondArr = secondObj[val] || [];
output[val] = firstArr.concat(secondArr);
})
document.body.innerHTML += JSON.stringify(output,0,4)
Upvotes: 1