JS:对象数组嵌套成对象

JS: array of objects into object with nesting

我需要转换这种数组:

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库。

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

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);