Convert parent-child array to tree

前端 未结 7 1855
感动是毒
感动是毒 2020-12-04 22:31

Can anyone help converting the following list of parent-child objects:

[
   {
      \"name\":\"root\",
      \"_id\":\"root_id\",
   },
   {
      \"name\":\"a1\"         


        
7条回答
  •  伪装坚强ぢ
    2020-12-04 23:05

    I know I'm too late, but since I just finished my contribution to a sample implementation of how this can be done I thought I would share it, since it might be found useful / or give inspiration to an alternative solution.

    The implementation can be found here: http://jsfiddle.net/sw_lasse/9wpHa/

    The main idea of the implementation centers around the following recursive function:

    // Get parent of node (recursive)
    var getParent = function (rootNode, rootId) {
    
        if (rootNode._id === rootId)
            return rootNode;
    
        for (var i = 0; i < rootNode.children.length; i++) {
            var child = rootNode.children[i];
            if (child._id === rootId)
                return child;
    
            if (child.children.length > 0)
                var childResult = getParent(child, rootId);
    
            if (childResult != null) return childResult;
        }
        return null;
    };
    

    ... that is used to build the tree.

提交回复
热议问题