Javier
Javier

Reputation: 2095

Method recursive to update a value down to top

I'm trying to make a recursive method that when you click on a hierarchy all parents will be enabled.

I know how to make recursive methods top to down, for example, find id one of children but I dont know how to make a recursive method down to top.

For example:

const data =  [{
    "id": 1,
    "parentId": null,
    "selected": false,
    "children": [{
        "id": 2,
        "parentId": 1,
        "selected": false,
        "children": [{
            "id": 3,
            "parentId": 2,
            "selected": false,
            "children": [{
                "id": 4,
                "parentId": 3,
                "selected": false,
                "children": []
            }]
        }]
    }]
 }, {
    "id": 1,
    "parentId": null,
    "selected": true,
    "children": []
 }, {
    "id": 1,
    "parentId": null,
    "selected": true,
    "children": []
 }]

When the item with id 4 is selected, the selected property of all its ancestors should be set to true.

Upvotes: 3

Views: 100

Answers (1)

Unmitigated
Unmitigated

Reputation: 89294

You can simply iterate until the parentId of the current node becomes null.

const data = [{ id: 1, parentId: null, selected: false, children: [{id: 2, parentId: 1, selected: false, children: [{id: 3, parentId: 2, selected: false, children: [{id: 4, parentId: 3, selected: false, children: []}]} ]} ] }, { id: 5, parentId: null, selected: true, children: [] }, { id: 6, parentId: null, selected: true, children: [] } ];
const getById = id => {
  const get = arr => {
    for(const x of arr){
      if(x.id === id) return x;
      const res = get(x.children || []);
      if(res) return res;
    }
  }
  return get(data);
}
let node = getById(4);
while(node.parentId != null){
  node = getById(node.parentId);
  node.selected = true;
}
console.log(data);

Upvotes: 5

Related Questions