'Change parent property in tree structure data by Recursive call in js
I am having the following object
let obj = {children:[
{
ID:1,
clicked: false,
children: [
{
ID:4,
clicked: false,
children: [
{
ID:11,
clicked: false,
children: [
{
ID:14,
clicked: true,
},
{
ID:15,
clicked: false,
}
]
},
{
ID:12,
clicked: false,
}
]
},
{
ID:5,
clicked: false,
}
]
}
]
}
I need to change the clicked property to true of a parent. so in this case ID - 14 is having clicked property to true. So, parents having ID 11,4,1 will also be having the same property to true.
In my understanding, DFS will be applied. I have tried the following code but not working in all cases
function reverseIt(obj) {
if(obj.children == undefined) {
return obj.clicked;
}
for(i = 0; i < obj.children.length; i++) {
if(!obj.children[i].clicked) {
obj.children[i].clicked = reverseIt(obj.children[i]);
}
return obj.children[i].clicked;
}
return true;
}
reverseIt(obj);
Solution 1:[1]
You need to change your function slightly:
let obj = {
children: [{
ID: 1,
clicked: false,
children: [{
ID: 4,
clicked: false,
children: [{
ID: 11,
clicked: false,
children: [{
ID: 14,
clicked: true,
},
{
ID: 15,
clicked: false,
}
]
},
{
ID: 12,
clicked: true,
}
]
},
{
ID: 5,
clicked: false,
}
]
}]
};
function reverseIt(obj) {
if (!obj.children) {
return obj;
}
if (obj.children.some(c => c.children)) {
obj.children = obj.children.map(child => reverseIt(child));
}
obj.clicked = obj.children[0].clicked;
return obj;
}
console.log(reverseIt(obj));
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jack Bashford |
