I have a nested object that I want to to transform to flat lines. Below is the object:
JavaScript
x
77
77
1
{
2
"United States": {
3
"New York": {
4
"first": 11,
5
"second": 7
6
},
7
"New Jersey": {
8
"first": 8,
9
"second": 2
10
},
11
"Pennsylvania": {
12
"first": 4,
13
"second": 2
14
}
15
}
16
},
17
{
18
"South America": {
19
"Brazil": {
20
"first": 5,
21
"second": 4
22
}
23
}
24
},
25
{
26
"Africa": {
27
"Zaire": {
28
"first": 2,
29
"second": 1
30
}
31
}
32
},
33
{
34
"Asia": {
35
"China": {
36
"first": 10,
37
"second": 4
38
},
39
"Japan": {
40
"first": 6,
41
"second": 3
42
}
43
}
44
},
45
{
46
"Eastern Europe": {
47
"Ukraine": {
48
"first": 2,
49
"second": 1
50
}
51
}
52
},
53
{
54
"Europe": {
55
"France": {
56
"first": 2,
57
"second": 4
58
},
59
"Germany": {
60
"first": 1,
61
"second": 7
62
},
63
"Portugal": {
64
"first": 3,
65
"second": 1
66
},
67
"Spain": {
68
"first": 5,
69
"second": 2
70
},
71
"Switzerland": {
72
"first": 1,
73
"second": 3
74
}
75
}
76
}
77
I want to be able to see it like this, where the top level of the nest is always visible for each line:
JavaScript
1
14
14
1
"United States", "New York", 11, 7
2
"United States", "New Jersey", 8, 2
3
"United States", "Pennsylvania", 4, 2
4
"South America":, "Brazil", 5, 4
5
"Africa", "Zaire", 2, 1
6
"Asia", "China", 10, 4
7
"Asia", "Japan", 6, 3
8
"Eastern Europe", "Ukraine", 2, 1
9
"Europe", "France", 2, 4
10
"Europe", "Germany", 1, 7
11
"Europe", "Portugal", 3, 1
12
"Europe", "Spain", 5, 2
13
"Europe", "Switzerland", 1, 3
14
I know how to loop through arrays to do this, but I’m not sure how to achieve it with a nested object. I’ve searched s/o, but haven’t seen anything that quite achieves this. (My actual data set is much longer) Any help is very welcome. Thank you.
Advertisement
Answer
Just perform a loop at each level of your structure:
JavaScript
1
9
1
let data = [{"United States": {"New York": {"first": 11,"second": 7},"New Jersey": {"first": 8,"second": 2},"Pennsylvania": {"first": 4,"second": 2}}},{"South America": {"Brazil": {"first": 5,"second": 4}}},{"Africa": {"Zaire": {"first": 2,"second": 1}}},{"Asia": {"China": {"first": 10,"second": 4},"Japan": {"first": 6,"second": 3}}},{"Eastern Europe": {"Ukraine": {"first": 2,"second": 1}}},{"Europe": {"France": {"first": 2,"second": 4},"Germany": {"first": 1,"second": 7},"Portugal": {"first": 3,"second": 1},"Spain": {"first": 5,"second": 2},"Switzerland": {"first": 1,"second": 3}}}];
2
3
for (let obj of data) {
4
for (let [region, countries] of Object.entries(obj)) {
5
for (let [country, indicators] of Object.entries(countries)) {
6
console.log(region, country, Object.values(indicators));
7
}
8
}
9
}