[removed] Find all parents for element in tree

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

    The easiest solution is to flatten the tree structure down so you can just look up ids and do a simple while loop

    var tree = {
      id: 1,
      children: [
      	{
    		id: 3,
    		parentId: 1,
    		children: [
    		  	{
    				id: 5,
    				parentId: 3,
    				children: []
    			}
    		]
    	}
      ]
    }
    
    // We will flatten it down to an object that just holds the id with the object
    var lookup = {}
    function mapIt (node) {
      lookup[node.id] = node;
      //recursive on all the children
      node.children && node.children.forEach(mapIt);
    }
    mapIt(tree)
    
    // This takes a node and loops over the lookup hash to get all of the ancestors
    function findAncestors (nodeId) {
       var ancestors = []
       var parentId = lookup[nodeId] && lookup[nodeId].parentId
       while(parentId !== undefined) {
         ancestors.unshift(parentId)
         parentId = lookup[parentId] && lookup[parentId].parentId
       }
       return ancestors;
    }
    
    // Let us see if it works
    console.log("5: ",  findAncestors(5))

提交回复
热议问题