I'm trying to merge these 2 arrays of object using lodash javascript library, when I do the merge the Subcategories property that contains another array is not merged. these are the arrays to be merged
var menu1 = [
{
"PageName": "Designer",
"Category": "Designer",
"LinkTo": "/",
"SubCategories": []
},
{
"PageName": "CMS",
"Category": "CMS",
"LinkTo": "",
"SubCategories": [
{
"Category": "Template DOP",
"LinkTo": "/sendoutboundmessages"
}
]
}];
var menu2 = [
{
"PageName": "CMS",
"Category": "CMS",
"LinkTo": "",
"SubCategories": [
{
"Category": "Cataloghi",
"LinkTo": "/catalogs-manager"
}
]
}
];
I'm trying with lodashJS in this way
const merged = _(menu1)
.keyBy('PageName')
.merge(_.keyBy(menu2, 'PageName'))
.values()
.value();
but It doesn't work for the SubCategory property that contains another array
The current output is this :
[
{
"PageName": "Designer",
"Category": "Designer",
"LinkTo": "/",
"SubCategories": []
},
{
"PageName": "CMS",
"Category": "CMS",
"LinkTo": "",
"SubCategories": [
{
"Category": "Cataloghi",
"LinkTo": "/catalogs-manager"
}
]
}
]
and I would like to have this output :
[
{
"PageName": "Designer",
"Category": "Designer",
"LinkTo": "/",
"SubCategories": []
},
{
"PageName": "CMS",
"Category": "CMS",
"LinkTo": "",
"SubCategories": [
{
"Category": "Cataloghi",
"LinkTo": "/catalogs-manager"
},
{
"Category": "Template DOP",
"LinkTo": "/sendoutboundmessages"
}
]
}
]
Thanks for the help.
SubCategoriesproperty is being merged, but you want a union of the 2 SubCategories arrays. According to the Lodash docs "Array and plain object properties are merged recursively." and "Subsequent sources overwrite property assignments of previous sources".