- 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,
}
]
}
]
}
CodePudding user response:
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; }
CodePudding user response:
Nina gave a great answer for when you want to mutate the input.
Here is a simple one which creates a new object:
const consolidate = ({clicked, children = [], ...rest}, _, __, kids = children .map (consolidate)) => ({
...rest,
clicked: clicked || (kids .length > 0) && kids .every (k => k .clicked),
...(kids .length ? {children: kids} : {})
})
const obj1 = {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}]}]};
// with 12 switched to `true`
const obj2 = {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: true}]}, {ID: 5, clicked: false}]}]};
console .log ('obj1', consolidate (obj1))
console .log ('obj2', consolidate (obj2))
.as-console-wrapper {max-height: 100% !important; top: 0}
We recur on the children
, if any, and then regenerate the object evaluating the clicked
property of each.