Search code examples
javascriptalgorithmtreedepth-first-search

JavaScript nth degree tree


  1. 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.
  2. 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

  • 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.