You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 18:45:40