I am trying to replace a nested object with an updated object with map. However, it only works if I replace each property but I cannot replace the entire object with the updated one. The following is my strucutre:
[
{
name: 'Parent 1',
data: [
{
id: 1,
name: 'Child 1',
// more properties ...,
},
{
id: 2,
name: 'Child 2',
// more properties ...
}
]
}
]
Now I want to replace a child in its parent with an updated child. This is what I have right now and it works but it isn't maintainable to map each property manually:
parents.map(parent =>
parent.data.map(child => {
if (child.id === newChild.id) {
child.name = newChild.name;
// more mappings ...
}
})
);
This is what doesn't work but the solution I would prefer:
parents.map(parent =>
parent.data.map(child => {
if (child.id === newChild.id) {
child= newChild;
}
})
);
I am also open to other solutions rather than using map. I am not sure if this is the correct way of doing it.