I am trying to change objects in nested map functions. I have one array of objects with nested data.
If I try to do on this way structure of data is changing. I'm getting array of arrays. Only what I need here is to add for each object one property "level". Is it possible to do this with nested map functions?
const res = data.map(itemA => ({ ...itemA,
level: 'a'
})
.subA.map(itemB => ({ ...itemB,
level: 'b'
})))
console.log(res)
<script>
let data = [{
name: 'testA1',
subA: [{
name: 'testB1',
subB: [{
name: 'testC1',
subC: []
}]
},
{
name: 'testB2',
subB: [{
name: 'testC1',
subC: []
}]
}
]
},
{
name: 'testA2',
subA: [{
name: 'testB1',
subB: [{
name: 'testC1',
subC: [{
name: 'testD1',
subD: []
}]
}]
}]
}
]
</script>
You can use a recursive function?
let data = [{ name: 'testA1', subA: [{ name: 'testB1', subB: [{ name: 'testC1', subC: [] }] }, { name: 'testB2', subB: [{ name: 'testC1', subC: [] }] } ] }, { name: 'testA2', subA: [{ name: 'testB1', subB: [{ name: 'testC1', subC: [{ name: 'testD1', subD: [] }] }] }] } ]
function addprop(arr, level){
arr.map(x=>{
const match = Object.keys(x).find(element => {
if (element.includes('sub')) {
return true;
}
});
addprop(x[match], level+1)
})
return arr.map(x=>(x.level=level,x))
}
console.log(addprop(data, 1))
Actually I did it on this way:
const res = data.map(itemA => (
{...itemA, level: 'a', subA: itemA.subA.map(itemB => (
{...itemB, level: 'b', subB: itemB.subB.map(itemC => (
{...itemC, level: 'c'}
))}
))}
))
console.log(res)
<script>
let data = [{
name: 'testA1',
subA: [{
name: 'testB1',
subB: [{
name: 'testC1',
subC: []
}]
},
{
name: 'testB2',
subB: [{
name: 'testC1',
subC: []
}]
}
]
},
{
name: 'testA2',
subA: [{
name: 'testB1',
subB: [{
name: 'testC1',
subC: [{
name: 'testD1',
subD: []
}]
}]
}]
}
]
</script>