Suppose, we have two child and parent JSON arrays of objects like these −
const child = [{
id: 1,
name: 'somename',
parent: {
id: 2
},
},
{
id: 2,
name: 'some child name',
parent: {
id: 4
}
}];
const parent = [{
id: 1,
parentName: 'The first',
child: {}
},
{
id: 2,
parentName: 'The second',
child: {}
},
{
id: 3,
parentName: 'The third',
child: {}
},
{
id: 4,
parentName: 'The fourth',
child: {}
}];We are required to write a JavaScript function that takes in these two arrays.
And our function should merge the child array objects into corresponding parent objects.
Therefore, the final output should look something like this −
const output = [
{
id: 1,
parentName: The first,
child: {}
},
{
id: 2,
parentName: The second,
child: {
id: 1,
name: somename,
}
},
{
id: 3,
parentName: The third,
child: {}
},
{
id: 4,
parentName: The fourth,
child: {
id: 2
name: some child name,
}
},
];Example
The code for this will be −
const child = [{
id: 1,
name: 'somename',
parent: {
id: 2
},
},
{
id: 2,
name: 'some child name',
parent: {
id: 4
}
}];
const parent = [{
id: 1,
parentName: 'The first',
child: {}
},
{
id: 2,
parentName: 'The second',
child: {}
},
{
id: 3,
parentName: 'The third',
child: {}
},
{
id: 4,
parentName: 'The fourth',
child: {}
}];
const combineParentChild = (parent, child) => {
const combined = [];
for (let i = 0; i < parent.length; i++) {
for (let j = 0; j < child.length; j++) {
if (child[j].parent.id === parent[i].id) {
parent[i].child.id = child[j].id;
parent[i].child.name = child[j].name;
break;
};
};
combined.push(parent[i])
};
return combined;
};
console.log(combineParentChild(parent, child));Output
And the output in the console will be −
[
{ id: 1, parentName: 'The first', child: {} },
{
id: 2,
parentName: 'The second',
child: { id: 1, name: 'somename' }
},
{ id: 3, parentName: 'The third', child: {} },
{
id: 4,
parentName: 'The fourth',
child: { id: 2, name: 'some child name' }
}
]