Use Array.prototype.map
instead, forEach
gets no returns
let newobj = [
{
id: 22,
reason: 'reason 2',
phase: 'phase 2',
reviewer: 'by user 2',
date: 'date 2'
},
{
id: 21,
reason: 'reason 1',
phase: 'phase 1',
reviewer: 'by user 1',
date: 'date 1'
}
];
let arr1 = {
initiateLevel: true,
parent: [
{
name: 'level1',
childrens: [
{
group: 'Level-group',
grandChildrens: [
{
id: 21,
technology: 'sp1',
path: 'l2',
reason: 'reason 1',
phase: 'phase 1',
reviewer: 'by user 1',
date: 'date 1'
},
{
id: 22,
technology: 'sp2',
path: 'l2',
reason: 'reason 2',
phase: 'phase 2',
reviewer: 'by user 2',
date: 'date 2'
}
]
}
]
},
{
name: 'level2',
childrens: [
{
group: 'Level-group-2',
grandChildrens: [
{
id: 121,
technology: 'sp12',
path: 'l4'
},
{
id: 122,
technology: 'sp22',
path: 'l4'
}
]
}
]
}
]
};
const merge = (y, z) => {
const parent = y.parent.map((element) => {
return {
...element,
childrens: element.childrens.map((x) => {
return {
...x,
grandChildrens: x.grandChildrens.map((test) => {
return { ...test, ...z.find((reviewItem) => reviewItem.id === test.id) };
})
};
})
}
});
return { ...y, parent };
};
const arr2 = merge(arr1, newobj);
console.log(arr2);
1
solved how to add object in nested array of objects without mutating original source