把普通对象列表转换为带有树结构的对象列表
发布于 1 年前 作者 William17 1348 次浏览 最后一次编辑是 9 个月前 来自 分享
[{
    id: 6,
    any: 'opps'
}, {
    id: 2,
    parent: 5,
    any: 'foo',
}, {
    id: 1,
    parent: 2,
    any: 'bar'
}, {
    id: 5,
    any: 'hello'
}, {
    id: 3,
    parent: 2,
    any: 'other'
}]

to

[{
    id: 6,
    any: 'opps',
    children: []
}, {
    id: 5,
    any: 'hello',
    children: [{
        id: 2,
        parent: 5,
        any: 'foo',
        children: [{
            id: 1,
            parent: 2,
            any: 'bar',
            children: []
        }, {
            id: 3,
            parent: 2,
            any: 'other',
            children: []
        }]
    }]
}]

刚好需要, 不太满意stackoverflow里的, 于是自己写了个…

function listToTree(data, options) {
    options = options || {};
    var ID_KEY = options.idKey || 'id';
    var PARENT_KEY = options.parentKey || 'parent';
    var CHILDREN_KEY = options.childrenKey || 'children';

    var tree = [],
        childrenOf = {};
    var item, id, parentId;

    for (var i = 0, length = data.length; i < length; i++) {
        item = data[i];
        id = item[ID_KEY];
        parentId = item[PARENT_KEY] || 0;
        // every item may have children
        childrenOf[id] = childrenOf[id] || [];
        // init its children
        item[CHILDREN_KEY] = childrenOf[id];
        if (parentId != 0) {
            // init its parent's children
            childrenOf[parentId] = childrenOf[parentId] || [];
            // push it into its parent's children
            childrenOf[parentId].push(item);
        } else {
            tree.push(item);
        }
    };

    return tree;
}

jsfiddle https://github.com/William17/list-to-tree-lite

回到顶部