I have a javascript array of objects like this:
// 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" },
//...
];
How do I convert it to something like this?
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"
}
]
}
],
//...
},
//...
];
I did some searching and found some very similar topics: Transform array to object tree [JS] array of strings to tree data structure But what I want is a combination of nested arrays and objects, instead of a tree of objects from the above solutions.
Please help me, thanks!
LongNameandsplit(';')to get an array of the names. Then loop through them creating a nested structure for each key until you get to the end. And then add the element with the fields you want