gpt4 book ai didi

javascript - 对象数组中属性值的递归数组

转载 作者:行者123 更新时间:2023-11-30 08:18:49 25 4
gpt4 key购买 nike

我需要的是一个属性值数组,从一个对象数组中递归收集,这就是我的意思:

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 数组中所有国家/地区代码的数组。

就像:

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
}, [])
}

最佳答案

您可以通过查找数组并返回代码来减少数组。

function getCodes(array) {
return array.reduce((r, o) => {
if ('code' in o) {
r.push(o.code);
return r;
}
Object.values(o).forEach(v => {
if (Array.isArray(v)) r.push(...getCodes(v));
});
return r;
}, []);
}

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' }] }],
codes = getCodes(regions);

console.log(codes);

关于javascript - 对象数组中属性值的递归数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57342010/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com