What I need is an array of property values, recursively collected from an array of objects, this is what I mean:
const regions = [{
name: 'Europe',
subRegions: [{
name: 'BeNeLux',
territories: [{
code: 'NL',
name: 'Netherlands'
}, {
code: 'DE',
name: 'Germany'
}, {
code: 'LU',
name: 'Luxembourgh'
}]
}],
territories: [{
code: 'UK',
name: 'United Kingdom'
}, {
code: 'AL',
name: 'Albania'
}, {
code: 'ZW',
name: 'Switzerland'
}]
}]
I want to get an array of all the country codes in the regions array.
So like:
const expectedOutput = ['NL', 'DE', 'LU', 'AL', 'ZW', 'UK'];
This what I have tried, which partly works but it's not collecting it correctly (I'm also very curious for exploring different / functional setups to solve this problem)
const getAllTerritoryCodesFromRegions = regions => {
return regions
.reduce(function r (output, region) {
if (region?.subRegions?.length) {
output.subRegions = region.subRegions.reduce(r, output)
}
if (region?.territories?.length) {
output = [
...output,
...region.territories.map(t => t.code)
]
}
return output
}, [])
}
codeproperty, the lower array has some country codes in thenameproperty? Is that a typo?