您的位置:首页 > 前端开发 > 技术笔记

js获取树状json里指定id的结点对象、指定id的父结点对象、指定id的上下文路径

2018-10-18 08:31:57

树状json如下

let treeData = [
    {
        id:'0',
        name:'项目组',
        children:[
            {
                id:'2',
                name:'材料组',
                children:[
                    {
                        id:'4',
                        name:'张三'
                    },
                    ...
                ]
            },
            ...
        ]
    },
    {
        id:'1',
        name:'策划组',
        children:[
            id:'3',
            name:'设计组',
            children:[]
        ]
    },
    ...
]


获取树中指定id的结点对象

const getNodeOfTree = (tree,id) => {
    let node = lodash.find(tree,{menuid:id});
    if(!node){
        for(let i=0;i<tree.length;i++){
            if(tree[i].children && tree[i].children.length>0){
                let cnode = getNodeOfTree(tree[i].children,id);
                if(cnode){
                    node = cnode; 
                    break;
                }
            }
        }
    }
    return node;
};

//调用
let user = getNodeOfTree(treeData,4);
console.log(user)
/*结果
    {
          id:'4',
          name:'张三'
     },
*/


获取树中指定id的父结点

const getParentNodeOfTree = (tree,id,parent) => {
    let p = null;
    for(let i=0;i<tree.length;i++){
        if(tree[i].id === id){
            p = parent;
            break;
        }else{
            if(tree[i].children && tree[i].children.length>0){
                p = getParentNodeOfTree(tree[i].children,id,tree[i]);
                if(p != null || p != undefined){
                    break;
                }
            }
        }
    }

    return p;
};

//调用
let cailiao = getParentNodeOfTree(treeData,4);
console.log(cailiao);
/*结果
    {
        id:'2',
        name:'材料组',
        children:[
            {
                id:'4',
                name:'张三'
            },
            ...
        ]
    },
*/


根据指定id找到其上下文路径

const getFullPathOfTree = (tree,id,path) => {
    if(!path) path = [];
    let node = getNodeOfTree(tree,id);
    if(node){
        path.unshift(node);
        let parent = getParentNodeOfTree(tree,id);
        if(parent){
            getFullPathOfTree(tree,parent.id,path);
        }
    }
    return path;
};
//调用
let path = getFullPathOfTree(treeData,4);
console.log(path);
/*结果
[
    {
        id:'0',
        name:'项目组',
        children:[]
    },
    {
        id:'2',
        name:'材料组',
        children:[]
    },
    {
        id:'4',
        name:'张三'
    }
]
*/


more 最近