【发布时间】:2021-01-02 10:34:48
【问题描述】:
我有一个像这样的 javascript 对象数组:
// Id is not necessarily unique, orderly or for any specific purpose
var input = [
{ Id: 1, LongName: "Europe;Germany;Frankfurt", Attribute1: "some attribute" },
{ Id: 2, LongName: "Europe;Germany;Munich", Attribute1: "some attribute" },
{ Id: 7, LongName: "Asia;Japan;Okinawa", Attribute1: "some attribute" },
{ Id: 8, LongName: "North America;US;Seattle", Attribute1: "some attribute" },
{ Id: 10, LongName: "Asia;China;Beijing", Attribute1: "some attribute" },
{ Id: 12, LongName: "Europe;France;Paris", Attribute1: "some attribute" },
{ Id: 14, LongName: "Europe;France;Marseille", Attribute1: "some attribute" },
{ Id: 5, LongName: "Asia;Japan;Tokyo", Attribute1: "some attribute" },
{ Id: 6, LongName: "Asia;Korea;Seoul", Attribute1: "some attribute" },
{ Id: 9, LongName: "Asia;Korea;Busan", Attribute1: "some attribute" },
{ Id: 11, LongName: "North America;US;New York", Attribute1: "some attribute" },
//...
];
如何将它转换成这样的东西?
var output = [
{
Name: "Europe",
Children: [
{
Name: "Germany",
Children: [
{
Name: "Frankfurt",
Id: 1,
Attribute1: "some attribute"
},
{
Name: "Munich",
Id: 2,
Attribute1: "some attribute"
}
]
},
{
Name: "France",
Children: [
{
Name: "Paris",
Id: 12,
Attribute1: "some attribute"
},
{
Name: "Marseille",
Id: 14,
Attribute1: "some attribute"
}
]
}
],
//...
},
//...
];
我做了一些搜索,发现了一些非常相似的主题: Transform array to object tree [JS] array of strings to tree data structure 但我想要的是嵌套数组和对象的组合,而不是上述解决方案中的对象树。
请帮帮我,谢谢!
【问题讨论】:
-
使用
LongName和split(';')获取名称数组。然后循环遍历它们,为每个键创建一个嵌套结构,直到你到达最后。然后用你想要的字段添加元素
标签: javascript arrays tree