JSFiddle - React, Tailwind, and code Playground
JavaScript
const getAllTerritoryCodesFromRegions = array => {
const output = [];
array.forEach(item => {
for (const key in item) {
if (key === 'code') {
output.push(item[key]);
} else if (item.hasOwnProperty(key) && Array.isArray(item[key])) {
const childOutput = getAllTerritoryCodesFromRegions(item[key]);
output.push(...childOutput);
}
}
});
return output;
}
const regions = [{
name: 'Europe',
subRegions: [{
name: 'BeNeLux',
territories: [{
code: 'NL',
name: 'Netherlands'
}, {
code: 'DE',
name: 'Germany'
}, {
code: 'LU',
name: 'Luxembourgh'
}]
}],
territories: [{
name: 'United Kingdom',
code: 'UK'
}, {
name: 'AL',
code: 'Albania'
}, {
name: 'ZW',
code: 'Switzerland'
}]
}]
const result = getAllTerritoryCodesFromRegions(regions)
console.log(result);