Answer the question
In order to leave comments, you need to log in
How to recursively change state in an array tree with objects?
There is a tree where the nesting of children can be unlimited. How to get recursively at each map iteration to children and change the state?
const data = [
{
id: 1, title: 'Article 1',
children: [
{
id: 1, title: 'Title Inside 1',
children: [
{
id: 1, title: 'Title Inside 2',
}
]
}]
},
{ id: 2, title: 'Article 2' },
Answer the question
In order to leave comments, you need to log in
something like this, if I understand correctly what needs to be done at all
obj = {
"id": 1,
"title": "Article 1",
"children": [
{
"id": 1,
"title": "Title Inside 1",
"children": [
{
"id": 11,
"title": "Title Inside 2",
"children": [
{
"id": 121,
"title": "Title Inside 4"
},
{
"id": 12341,
"title": "Title Inside 6"
}
]
}
]
}
]
}
function fn(obj, upd) {
obj = {...obj, ...upd}
if(Array.isArray(obj.children)) {
obj.children = obj.children.map(child => fn(child, upd))
}
return obj
}
fn(obj, { id: 2, title: 'Article 2' })
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question