[removed] Find all parents for element in tree

前端 未结 4 644
天命终不由人
天命终不由人 2020-12-30 18:00

I have the objects tree, and i can\'t found all parents for concrete object id. Imagine i need to add some new field to each parent for object with id = 5. Can someone help

4条回答
  •  别那么骄傲
    2020-12-30 18:14

    A recursion function isn't that difficult. Remember that you pass the new level onto the function if your parameter isn't met.

    var tree = [{
      id: 1,
      children: [{
        id: 3,
        parentId: 1,
        children: [{
          id: 5,
          parentId: 3,
          children: [{
            id: 6,
            parentId: 5,
            children: [{
              id: 5,
              parentId: 3,
              children: []
            }]
          }]
        }]
      }]
    }]; //wrap first obj in an array too.
    
    searchTree(tree, 5);
    console.log(tree);
    
    function searchTree(tree, nodeId) {
      for (let i = 0; i < tree.length; i++) {
        if (tree[i].id == nodeId) {
          tree[i]; //id found, now add what you need.
          tree[i].newField = "added";
        }//if child has children of its own, continu digging.
        if (tree[i].children != null && tree[i].children.length > 0) {
          searchTree(tree[i].children, nodeId); //pass the original nodeId and if children are present pass the children array to the function.
    
        }
      }
    }

提交回复
热议问题