如何在JavaScript中从对象内的数组提取并合并数据?
提取并合并嵌套城市数组的实现方法
你可以通过以下几种方式实现需求:
方法一:使用Object.values() + map() + flat()
这种方式简洁直观,先提取所有国家对象,再取出每个对象的cities数组,最后扁平化合并成一维数组:
const countries = { italy: { id: 1, cities: ["Rome", "Milan"], }, spain: { id: 2, cities: ["Barselona", "Madrid"], } }; function getCitiesDates(data) { const countryObjects = Object.values(data); return countryObjects.map(country => country.cities).flat(); } // 调用测试 console.log(getCitiesDates(countries)); // 输出: ["Rome", "Milan", "Barselona", "Madrid"]
方法二:使用Object.values() + 扩展运算符... + concat()
如果需要兼容不支持flat()的旧环境,可以用concat配合扩展运算符实现合并:
function getCitiesDates(data) { const countryObjects = Object.values(data); return [].concat(...countryObjects.map(country => country.cities)); }
方法三:传统遍历方式
如果想更清晰地看到每一步的收集过程,也可以用for循环手动处理:
function getCitiesDates(data) { const result = []; for (const country of Object.values(data)) { result.push(...country.cities); } return result; }
以上几种方法都能实现将嵌套的城市数组合并为目标一维数组,你可以根据自己的代码习惯和运行环境选择合适的方案。
内容的提问来源于stack exchange,提问作者KomarCorporation
相关产品推荐
相关产品推荐

