gpt4 book ai didi

javascript - JS : array of objects into object with nesting

转载 作者:行者123 更新时间:2023-11-27 22:55:33 27 4
gpt4 key购买 nike

我需要转换这种数组:

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 个嵌套,也可能更多(定义为数组中的间距)。我怎样才能做到这一点?我只能使用纯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);

关于javascript - JS : array of objects into object with nesting,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37656724/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com