我需要的是一个属性值数组,从对象数组中递归收集,这就是我的意思:
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'
}]
}]
我想获取所有国家/地区代码的数组regions
array.
So like:
const expectedOutput = ['NL', 'DE', 'LU', 'AL', 'ZW', 'UK'];
这是我尝试过的,部分有效,但没有正确收集它(我也很好奇探索不同/功能设置来解决这个问题)
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
}, [])
}