'JavaScript nth degree tree
- I need to change the clicked property to true of a parent if all children clicked are true. so in this case ID - 14,15 is having clicked property to true. So, parents having ID 11 clicked has to be made true.
- If 11,12,14,15 are true then then 4 has to be made true.
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: true,
}
]
},
{
ID:12,
clicked: false,
}
]
},
{
ID:5,
clicked: false,
}
]
}
]
}
Solution 1:[1]
You could take a depth-first search algorithm and if all of the children contains clicked: true, the parent gets an update.
const
update = object => {
if (!object.children) return object.clicked;
return object.clicked = object.children.every(update);
},
object = { children: [{ ID: 1, clicked: false, children: [{ ID: 4, clicked: false, children: [{ ID: 11, clicked: false, children: [{ ID: 14, clicked: true }, { ID: 15, clicked: true }] }, { ID: 12, clicked: false }] }, { ID: 5, clicked: false }] }] };
update(object);
console.log(object);
.as-console-wrapper { max-height: 100% !important; top: 0; }
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 |
