Struggling to merge these two arrays? Look no further! By comparing the parent id
to child parentsId
, you can effortlessly push the second array as an extra property to its parent. Save yourself hours of frustration and achieve your desired output with a little help.
Array 1
const parent = [
{
id: 1,
name: 'john',
age: 32,
},
{
id: 2,
name: 'jane',
age: 44,
},
];
Array 2
const child = [
{
parentId: 1,
name: 'mike',
age: 5,
},
{
parentId: 2,
name: 'michelle',
age: 6,
},
{
parentId: 2,
name: 'morgan',
age: 7,
},
];
Desired result: Populate the child elements into their respective parent objects based on parentId.
const parent = [
{
id: 1,
name: 'john',
age: 32,
children: [
{
parentId: 1,
name: 'mike',
age: 5,
},
],
},
{
id: 2,
name: 'jane',
age: 44,
children: [
{
parentId: 2,
name: 'michelle',
age: 6,
},
{
parentId: 2,
name: 'morgan',
age: 7,
},
],
},