获取树列表级别 - JavaScript

时间:2017-08-03 14:12:18

标签: javascript jquery recursion treeview

我有一个javascript函数,它将平面树列表转换为多维数组。我希望此函数还为每个项添加tree_level属性。

    function getNestedChildren(arr, parent) {
    var out = []
    for (var i in arr) {    
            if (arr[i].headerId == parent) {
                var children = getNestedChildren(arr, arr[i].workID)

                if (children.length) {
                    arr[i].children = children
                }
                out.push(arr[i])
            }
    }
    return out
}

2 个答案:

答案 0 :(得分:1)

添加树级参数:

function getNestedChildren(arr, parent, level) {
    var out = []
    for (var i in arr) {  
            if (arr[i].headerId == parent) {
                arr[i].level = level;

                var children = getNestedChildren(arr, arr[i].workID, level + 1)

                if (children.length) {
                    arr[i].children = children
                }
                out.push(arr[i])
            }
    }
    return out
}

答案 1 :(得分:0)

你的初始函数经过n次数组n次并改变了它的参数。

O(n)ES6解决方案,不会改变其论点:

function getNestedChildren(arr, root) {
    const empty = [];
    const childrenOf = {};

    // build a dictionary containing all nodes keyed on parent
    arr.forEach((node) => {
        if (!childrenOf[node.headerId]) childrenOf[node.headerId] = [];
        childrenOf[node.headerId].push(node);
    });

    // attach children to their parents and decorate with level
    const iterateHash = (parent, level) => {
        const nodes = childrenOf[parent] || empty;
        return nodes.map((node) => {
            const children = iterateHash(node.workId, level + 1);
            // remove the first argument {} to mutate arr
            return Object.assign({}, node, { level, children });
        });
    };

    return iterateHash(root, 0);
}