I have incoming data in this format:
JavaScript
x
38
38
1
const worldMap = [
2
{
3
"name": "Germany",
4
"parentId": null,
5
"type": "Country",
6
"value": "country:unique:key:1234",
7
"id": "1",
8
},
9
{
10
"name": "North Rhine",
11
"parentId": "1",
12
"type": "State",
13
"value": "state:unique:key:1234",
14
"id": "2",
15
},
16
{
17
"name": "Berlin",
18
"parentId": "1",
19
"type": "State",
20
"value": "state:unique:key:1234",
21
"id": "3",
22
},
23
{
24
"name": "Dusseldorf",
25
"parentId": "2",
26
"type": "city",
27
"value": "city:unique:key:1234",
28
"id": "4",
29
},
30
{
31
"name": "India",
32
"parentId": null,
33
"type": "Country",
34
"value": "country:unique:key:1234",
35
"id": "5",
36
},
37
];
38
I want the output to be something like this:
JavaScript
1
28
28
1
[
2
{
3
label: "Germany",
4
value: "country:unique:key:1234",
5
subs: [
6
{
7
label: "North Rhine",
8
value: "state:unique:key:1234",
9
subs: [
10
{
11
label: "Dusseldorf",
12
value: "city:unique:key:1234",
13
}
14
]
15
},
16
{
17
label: "Berlin",
18
value: "state:unique:key:1234",
19
}
20
]
21
}
22
,
23
{
24
"label": "India",
25
"value": "country:unique:key:1234"
26
}
27
]
28
Basically, it is a three dimensional array with first level being the Countrie, second States and third Cities. I have tried the following code:
JavaScript
1
17
17
1
let tempCountries = [];
2
3
worldMap.map((world) => {
4
if (world.parentId == null && world.type == "Country") {
5
tempCountries.push({label: world.name, value: world.value, id: world.id});
6
}
7
});
8
9
10
tempCountries.map((tempCountry) => {
11
const states = worldMap.find((x) => x.parentId == tempCountry.id);
12
console.log("=== states ===", states);
13
if (states !== undefined) {
14
tempCountries.find((x)=>x.id == tempCountry.id).children.push(states)
15
}
16
});
17
But the above code works upto second level and does not add cities to states. Could anyone please help me achieve this ?
Thanks a lot!
Advertisement
Answer
You can use a recursive solution:
JavaScript
1
21
21
1
function convertToTree(layer, parentId = null) {
2
const vertex = new Map(), others = [];
3
4
layer.forEach(item => {
5
if (item.parentId === parentId) {
6
vertex.set(item.id, { label: item.name, value: item.value });
7
} else {
8
others.push(item);
9
}
10
});
11
12
for (const vertexId of vertex.keys()) {
13
const subs = convertToTree(others, vertexId);
14
if (subs.length) {
15
vertex.get(vertexId).subs = subs;
16
}
17
}
18
19
return [vertex.values()];
20
}
21