JS:嵌套对象的对象数组

时间:2016-06-06 11:51:36

标签: javascript lodash

我需要转换这种数组:

const obj = [{
    name: 'firstLink',
    type: 'topic',
    id: 'ab75ca14-dc7c-4c3f-9115-7b1b94f88ff6',
    spacing: 1, // root
}, {
    name: 'secondLink',
    type: 'source',
    id: 'd93f154c-fb1f-4967-a70d-7d120cacfb05',
    spacing: 2, // child of previous object
}, {
    name: 'thirdLink',
    type: 'topic',
    id: '31b85921-c4af-48e5-81ae-7ce45f55df81',
    spacing: 1, // root
}]

进入这个对象:

const map = {
    'ab75ca14-dc7c-4c3f-9115-7b1b94f88ff6': {
        name: 'firstLink',
        type: 'topic',
        children: {
            'd93f154c-fb1f-4967-a70d-7d120cacfb05': {
                name: 'secondLink',
                type: 'source',
            }
        },
    },
    '31b85921-c4af-48e5-81ae-7ce45f55df81': {
        name: 'thirdLink',
        type: 'topic',
    }
}

最多可能有10个嵌套,可能更多(在数组中定义为spacing)。 我怎样才能做到这一点?我只能使用纯js和lodash库。

1 个答案:

答案 0 :(得分:1)

您可以使用数组作为插入的嵌套对象的引用。



var obj = [{ name: 'firstLink', type: 'topic', id: 'ab75ca14-dc7c-4c3f-9115-7b1b94f88ff6', spacing: 1, }, { name: 'secondLink', type: 'source', id: 'd93f154c-fb1f-4967-a70d-7d120cacfb05', spacing: 2, }, { name: 'thirdLink', type: 'topic', id: '31b85921-c4af-48e5-81ae-7ce45f55df81', spacing: 1, }],
    map = {};

obj.forEach(function (a) {
    this[a.spacing - 1][a.id] = { name: a.name, type: a.type, children: {}};
    this[a.spacing] = this[a.spacing - 1][a.id].children;
}, [map]);

console.log(map);




如果您不喜欢空children个对象,则可以使用此提案。它仅在必要时才创建children属性。



var obj = [{ name: 'firstLink', type: 'topic', id: 'ab75ca14-dc7c-4c3f-9115-7b1b94f88ff6', spacing: 1, }, { name: 'secondLink', type: 'source', id: 'd93f154c-fb1f-4967-a70d-7d120cacfb05', spacing: 2, }, { name: 'thirdLink', type: 'topic', id: '31b85921-c4af-48e5-81ae-7ce45f55df81', spacing: 1, }],
    map = {};

obj.forEach(function (a) {
    this[a.spacing - 1].children = this[a.spacing - 1].children || {};
    this[a.spacing - 1].children[a.id] = { name: a.name, type: a.type};
    this[a.spacing] = this[a.spacing - 1].children[a.id];
}, [map]);

map = map.children;
console.log(map);