[removed] Find all parents for element in tree

前端 未结 4 643
天命终不由人
天命终不由人 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:24

    Here is an example of a working recursive function.

    Play around with it for a while and you should be golden

    var tree = {
      id: 1,
      children: [{
        id: 3,
        parentId: 1,
        children: [{
          id: 5,
          parentId: 3,
          children: []
        }]
      }]
    }
    
    function mapit(node, parent = null) {
      node.parent = parent;
      if (node.children.length > 0) {
        for (var i = 0; i < node.children.length; i++) {
          var child = node.children[i];
          mapit(child, node);
        }
      }
    }
    mapit(tree);
    console.log(tree);

提交回复
热议问题