Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
569 views
in Technique[技术] by (71.8m points)

js怎么实现递归生成tree结构数据

原始数据形式为

var data = [
    { id: 1, name: "节点1", pid: 0 },
    { id: 2, name: "节点2", pid: 1 },
    { id: 3, name: "节点3", pid: 1 },
    { id: 4, name: "节点4", pid: 2 },
    { id: 5, name: "节点5", pid: 0 },
    { id: 6, name: "节点6", pid: 5 },
    { id: 7, name: "节点7", pid: 6 },
    { id: 8, name: "节点8", pid: 6 },
];

希望得到的结构是

var data = [
    {id: 1, name: "节点1", pid: 0 ,
        children:[
            { id: 2, name: "节点2", pid: 1,
                children:[
                    { id: 4, name: "节点4", pid: 2 },
                ],
            },
            { id: 3, name: "节点3", pid: 1},
        ]
    },
    {id: 5, name: "节点5", pid: 0 ,
        children:[
            { id: 6, name: "节点6", pid: 5,
                children:[
                    { id: 7, name: "节点7", pid: 6 },
                    { id: 8, name: "节点8", pid: 6 },
                ]
            },
        ]
    },
];

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
function getTree(ary, pid = 0) {
  return ary.filter(v => v.pid === pid).map(v => {
    const children = getTree(ary, v.id);
    if (children.length) v.children = getTree(ary, v.id);
    return v
  });
}

这样写会在原数组上添加children,不想修改原数组就在map里面做个浅拷贝


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...