I want to merge two arrays of objects. Those objects have the same structure, but one of them is missing the hide property. I want to copy the value of hide property from one object to the other that is missing this property. The important part is that I don't want to mutate any of these arrays!
The first array looks like this (notice that there is hide property):
let first_array = [
{
name: 'John',
age: 40,
hide: true,
childs: [
{
name: 'Alice',
age: 20,
hide: false,
childs: [
{
name: 'Mike',
age: 2,
hide: true
}
]
}
]
},
{
name: 'Peter',
age: 40,
hide: true,
childs: [
{
name: 'Andrew',
age: 20,
hide: true,
childs: [
{
name: 'Jessica',
age: 2,
hide: true
}
]
}
]
}
]
The second array looks almost the same! The only thing missing is hide property.
let second_array = [
{
name: 'John',
age: 40,
childs: [
{
name: 'Alice',
age: 20,
childs: [
{
name: 'Mike',
age: 2,
}
]
}
]
},
{
name: 'Peter',
age: 40,
childs: [
{
name: 'Andrew',
age: 20,
childs: [
{
name: 'Jessica',
age: 2,
}
]
}
]
}
]
Now, I want to create new array with where within each object there is hide property.
I know how to do this recursively in the imperative
way, but unfortunately I'm mutating data - which I don't want to do.
function getHideProperty(first, second) {
for (let i = 0; i < second.length; i++) {
for (let j = 0; j < first.length; j++) {
if (second[i].name === first[j].name) {
second[i].hide = first[j].hide
if (second[i].childs) {
second[i].childs = getHideProperty(first[j].childs, second[i].childs)
}
}
}
}
return second
}
Now I can create new array with merged objects:
const newArray = getHideProperty(second_array, first_array)
Now, every object in second_array has hide property. But I mutated the array :(
How to achieve such result without mutating the array?