In my data structure, I have parent objects with nested arrays of children. Here's an example:
[
{
"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 want to combine parent nodes with the same 'fullName' and merge their children together. The desired result 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",
}
]
}
]
I've tried various lodash solutions based on different resources, but haven't quite achieved the desired output. Do you have any suggestions or ideas?
@Andy, one solution that seemed promising was the following function:
function mergeNames (arr) {
return _.chain(arr).groupBy('fullName').mapValues(function (v) {
return _.chain(v).map('fullName').flattenDeep();
}).value();
}
console.log(mergeNames(array));
However, this outputs a "lodash wrapper" and doesn't correctly combine the children. I suspect this might be because of having the same identifier (fullName) at both child and parent levels. Running this code provides the following console output:
{
"Certificate": [
"Certificate"
],
"InstalledPackage": [
"InstalledPackage",
"InstalledPackage"
],
"Network": [
"Network"
]
}