怎样效率高的生成树形结构的数据?

比如原始数据:

let data = [
    {id: 1, name:'a', parent_id: 0},
    {id: 2, name:'b', parent_id: 0},
    {id: 3, name:'a-1', parent_id: 1},
    {id: 4, name:'a-2', parent_id: 1},
    {id: 5, name:'b-1', parent_id: 2},
    {id: 6, name:'b-2', parent_id: 2},
    {id: 7, name:'a-1-1', parent_id: 3},
]

重构成:

let data2 = [
    {id: 1, name:'a', parent_id: 0, children: [{id: 3, name:'a-1', parent_id: 1....},...]},
    {id: 2, name:'b', parent_id: 0, children: [{id: 5, name:'b-1', parent_id: 2....},...]},
]

谢谢!

阅读 5.1k
2 个回答

以前写过类似的。改了改给你:

    let data = [{
        id: 1,
        name: 'a',
        parent_id: 0
    }, {
        id: 2,
        name: 'b',
        parent_id: 0
    }, {
        id: 3,
        name: 'a-1',
        parent_id: 1
    }, {
        id: 4,
        name: 'a-2',
        parent_id: 1
    }, {
        id: 5,
        name: 'b-1',
        parent_id: 2
    }, {
        id: 6,
        name: 'b-2',
        parent_id: 2
    }, {
        id: 7,
        name: 'a-1-1',
        parent_id: 3
    }, ];
    let result = data.reduce(function(prev, item) {
        prev[item.parent_id] ? prev[item.parent_id].push(item) : prev[item.parent_id] = [item];
        return prev;
    }, {});
    for (let prop in result) {
        result[prop].forEach(function(item, i) {
            result[item.id] ? item.children = result[item.id] : ''
        });
    }
    result = result[0];
    console.log(JSON.stringify(result))

你是在使用ztree树吧,不需要重构,使用ztree树的simpledata格式,然后指定idKey和pIdKey即可

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏