{ "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", } ]
}
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:
getRecursive() { if (Array.isArray(data)) { for (let i = 0; i < data.length; i++) { if (data[i].subscriptions) { return data[i].subscriptions.map((val: SubscriptionGroupDetails) => val.topic); } else if (data[i].groups) { return this.getAllTopics(data[i].groups); } } } if (data && data.groups) { return this.getAllTopics(data.groups); } return data.subscriptions.map((val: SubscriptionGroupDetails) => val.topic); }
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.
function getTopics(object) { if (!object || typeof object !== 'object') return []; if ('topic' in object) return [object.topic]; return Object.values(object).reduce((r, v) => [...r, ...getTopics(v)], []); } 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" }] }, result = getTopics(data); console.log(result);