美文网首页
【JS】树形数据生成

【JS】树形数据生成

作者: 睡神疯子 | 来源:发表于2020-05-28 22:27 被阅读0次
    // mockData
    var data = [
            {"id": "1", "name": "a", "pid": "0"},
            {"id": "1.1", "name": "a1", "pid": "1"},
            {"id": "1.2", "name": "a2", "pid": "1"},
            {"id": "2", "name": "b", "pid": "0"},
            {"id": "2.1", "name": "b1", "pid": "2"},
            {"id": "2.2", "name": "b2", "pid": "2"}
        ];
    

    生成经典 tree 数据

        function createTree(id, data) {
            let tree = []
            data.forEach((item, i) => {
                if(id == item.pid) {
                    tree.push({
                        label: item.name,
                        children: createTree(item.id, data)
                    })
                }
            })
            return tree
        }
        console.log(createTree(0, data))
    

    相关文章

      网友评论

          本文标题:【JS】树形数据生成

          本文链接:https://www.haomeiwen.com/subject/irnjvhtx.html