I'm currently facing an issue with comparing 2 arrays of objects and I couldn't find a suitable method in the lodash documentation. The challenge lies in comparing objects using different keys.
private parentArray: {}[] = [
{ Id: 1, Name: 'A' },
{ Id: 2, Name: 'B' },
{ Id: 3, Name: 'C' },
{ Id: 4, Name: 'D' }
];
private childArray: {}[] = [
{ Id: 2, parentId: 2, Name: 'a' },
{ Id: 3, parentId: 2, Name: 'b' },
{ Id: 4, parentId: 4, Name: 'c' },
{ Id: 5, parentId: 4, Name: 'd' }
];
My goal is to create a new array of nested objects where 'parentId' matches the 'Id' of the parent objects. The desired output should be like this:
private newArray = [
{ Id: 1, Name: 'A', Children: [] },
{
Id: 2,
Name: 'B',
Children: [
{ Id: 2, parentId: 2, Name: 'a' },
{ Id: 3, parentId: 2, Name: 'b' }
]
},
{
Id: 3,
Name: 'C',
Children: []
},
{
Id: 4,
Name: 'D',
Children: [
{ Id: 4, parentId: 4, Name: 'c' },
{ Id: 5, parentId: 4, Name: 'd' }
]
}
];
I've tried using '.intersectionWith([arrays], [comparator])' and '.isMatchWith(object, source, [customizer])' but haven't been able to achieve the desired result. Any help would be greatly appreciated.