I have an array of parent objects with nested array of children in a structure like so:
[
{
"fullName": "Certificate",
"checked": false,
"children": [
{
"type": "Certificate",
"lastModifiedDate": "1971-01-01T00:00:00.000Z",
"fullName": "Certificate-1",
}
]
},
{
"fullName": "InstalledPackage", "checked": false, "children": [ { "type": "InstalledPackage", "lastModifiedDate": "1971-01-01T00:00:00.000Z", "fullName": "Package1", } ] }, { "fullName": "InstalledPackage", "checked": false, "children": [ { "type": "InstalledPackage", "lastModifiedDate": "1971-01-01T00:00:00.000Z", "fullName": "Package2", } ] },
{
"fullName": "Network",
"checked": false,
"children": [
{
"type": "InstalledPackage",
"lastModifiedDate": "1971-01-01T00:00:00.000Z",
"fullName": "Network1",
}
]
}
]
I would like to merge any parent nodes with the same 'fullName' while pushing the children together. The desired output is:
[
{
"fullName": "Certificate",
"checked": false,
"children": [
{
"type": "Certificate",
"lastModifiedDate": "1971-01-01T00:00:00.000Z",
"fullName": "Certificate-1",
}
]
},
{
"fullName": "InstalledPackage", "checked": false, "children": [ { "type": "InstalledPackage", "lastModifiedDate": "1971-01-01T00:00:00.000Z", "fullName": "Package1", }, { "type": "InstalledPackage", "lastModifiedDate": "1971-01-01T00:00:00.000Z", "fullName": "Package2", } ] },
{
"fullName": "Network",
"checked": false,
"children": [
{
"type": "InstalledPackage",
"lastModifiedDate": "1971-01-01T00:00:00.000Z",
"fullName": "Network1",
}
]
}
]
Is there an elegant way of achieving this (with lodash or other)? I have tried a number of looping solutions based on answers found here but I haven't been able to get it quite right. Any ideas?
@Andy, most of the code I have tried has been based on the answers found in the hyperlink, one attempt that looked promising was:
function mergeNames (arr) {
return _.chain(arr).groupBy('fullName').mapValues(function (v) {
return _.chain(v).map('fullName').flattenDeep();
}).value();
}
console.log(mergeNames(array));
But the output of this is a "lodash wrapper"? and doesn't quite correctly push the children together - I think perhaps because I have the same identifier (fullName) at both the child and parent level? When I run this code and copy the output from chrom console, i get the following:
{
"Certificate": [
"Certificate"
],
"InstalledPackage": [
"InstalledPackage",
"InstalledPackage"
],
"Network": [
"Network"
]
}