【发布时间】:2023-03-12 05:03:01
【问题描述】:
我在尝试将平面对象数组转换为基于 name 属性的嵌套对象数组时遇到问题。
将input 数组转换为类似于desiredOutput 数组结构的最佳方法是什么?
var input = [
{
name: 'foo',
url: '/somewhere1',
templateUrl: 'foo.tpl.html',
title: 'title A',
subtitle: 'description A'
},
{
name: 'foo.bar',
url: '/somewhere2',
templateUrl: 'anotherpage.tpl.html',
title: 'title B',
subtitle: 'description B'
},
{
name: 'buzz.fizz',
url: '/another/place',
templateUrl: 'hello.tpl.html',
title: 'title C',
subtitle: 'description C'
},
{
name: 'foo.hello.world',
url: '/',
templateUrl: 'world.tpl.html',
title: 'title D',
subtitle: 'description D'
}
]
var desiredOutput = [
{
name: 'foo',
url: '/somewhere1',
templateUrl: 'foo.tpl.html',
data: {
title: 'title A',
subtitle: 'description A'
},
children: [
{
name: 'bar',
url: '/somewhere2',
templateUrl: 'anotherpage.tpl.html',
data: {
title: 'title B',
subtitle: 'description B'
}
},
{
name: 'hello',
data: {},
children: [
{
name: 'world',
url: '/',
templateUrl: 'world.tpl.html',
data: {
title: 'title D',
subtitle: 'description D'
}
}
]
}
]
},
{
name: 'buzz',
data: {},
children: [
{
name: 'fizz',
url: '/',
templateUrl: 'world.tpl.html',
data: {
title: 'title C',
subtitle: 'description C'
}
}
]
}
]
请注意,输入数组中对象的顺序无法保证。 此代码将在 Node.js 环境中运行,我愿意使用 lodash 等库来实现所需的输出。
非常感谢任何帮助。
【问题讨论】:
-
请在您的问题中添加您的代码
-
我的代码不能比问题长,所以 Stackoverflow 不允许我这样做。因此粘贴箱链接。我希望数据集足够详细,以充分表达问题。
-
所以父子关系是基于
input[].name拆分.?或者你能进一步确定这种关系吗? -
@matt_d_rat 你当然可以,而且你需要!在您的问题本身中包含代码。不是每个人都可以访问外部网站,并且链接可能会随着时间的推移而中断。
-
@Magicprog.fr 好吧,这很奇怪,当我编辑它时它让我这样做了。我第一次发帖时没有。很奇怪。
标签: javascript arrays tree javascript-objects lodash