JavaScript
x
51
51
1
{
2
"groups": [
3
{
4
"name": "Event",
5
"groups": [
6
{
7
"name": "Service",
8
"subscriptions": [
9
{
10
"topic": "SERVICE_STATUS_PRESETS"
11
},
12
{
13
"topic": "AIRCRAFT_ACTIVATION",
14
15
},
16
{
17
"topic": "OUT_OF_SERVICE",
18
19
}
20
]
21
}
22
]
23
},
24
{
25
"name": "Enquiries",
26
"groups": [
27
{
28
"name": "Service-related",
29
"subscriptions": [
30
{
31
32
"topic": "PROMO_CODES_REQUESTS",
33
34
}
35
]
36
}
37
]
38
}
39
],
40
"subscriptions": [
41
{
42
"topic": "BANNERS",
43
},
44
{
45
"topic": "DOCUMENTS",
46
},
47
{
48
"topic": "USER",
49
}
50
]
51
}
OK guys I have such JSON structure what I need is to: return all topics in array, in this example it will be:
[“SERVICE_STATUS_PRESETS”, “AIRCRAFT_ACTIVATION”, “OUT_OF_SERVICE”, “PROMO_CODES_REQUESTS”, “BANNERS”, “DOCUMENTS”, “USER”]
I try recursive calls like this, though I only get last three records:
JavaScript
1
16
16
1
getRecursive() {
2
if (Array.isArray(data)) {
3
for (let i = 0; i < data.length; i++) {
4
if (data[i].subscriptions) {
5
return data[i].subscriptions.map((val: SubscriptionGroupDetails) => val.topic);
6
} else if (data[i].groups) {
7
return this.getAllTopics(data[i].groups);
8
}
9
}
10
}
11
if (data && data.groups) {
12
return this.getAllTopics(data.groups);
13
}
14
return data.subscriptions.map((val: SubscriptionGroupDetails) => val.topic);
15
}
16
Advertisement
Answer
You could take a recursive approach and check
- if the handed over data is not an object for checking, then return with empty array,
- if the object has the wanted property, then return an array with the value of
topic
, - or get the values and make a recursive call with the function and return an array with the result of it.
JavaScript
1
10
10
1
function getTopics(object) {
2
if (!object || typeof object !== 'object') return [];
3
if ('topic' in object) return [object.topic];
4
return Object.values(object).reduce((r, v) => [r, getTopics(v)], []);
5
}
6
7
var data = { groups: [{ name: "Event", groups: [{ name: "Service", subscriptions: [{ topic: "SERVICE_STATUS_PRESETS" }, { topic: "AIRCRAFT_ACTIVATION" }, { topic: "OUT_OF_SERVICE" }] }] }, { name: "Enquiries", groups: [{ name: "Service-related", subscriptions: [{ topic: "PROMO_CODES_REQUESTS" }] }] }], subscriptions: [{ topic: "BANNERS" }, { topic: "DOCUMENTS" }, { topic: "USER" }] },
8
result = getTopics(data);
9
10
console.log(result);