一只小开发仔...

JavaScript 构建树形Tree数据以及获取指定节点完整路径

34 2021-04-12 10:25:51
/**
* zNodes = [{id=1,pid=0,name="xxx"...}...]
*/
function getTreeData(zNodes = []) {
    var maps = {};
    zNodes.forEach(function(item, idx) {
        maps[item.id] = item;
    });

    var tree = [];
    zNodes.forEach(function(item, idx) {
        var parent = maps[item.pid]
        if (parent) {
            (parent.children || (parent.children = [])).push(item);
        } else {
            tree.push(item);
        }
    });
    return tree;
}

/**
 * value 值
 * key 字段名称
 * tree 树形结构数组数组
 */
function getTreePathByKey(value, key, tree) {
    let treePath = [];
    try {
        function getNodePath(node) {
            treePath.push(node);
            if (node[key] == value) {
                throw ("GOT IT!");
            }
            if (node.children && node.children.length > 0) {
                for (var i = 0; i < node.children.length; i++) {
                    getNodePath(node.children[i]);
                }
                treePath.pop();
            } else {
                treePath.pop();
            }
        }
        for (let i = 0; i < tree.length; i++) {
            getNodePath(tree[i]);
        }
    } catch (e) {}
    return treePath;
}