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

如何聚合大洲与国家对象并替换元素?代码报错求助

问题分析与修复:将地区数组转换为大洲-国家映射对象

需求说明

我有一个JSON对象数组,需要生成以大洲为键、对应国家数组为值的对象(示例:{"Asia":['India','China'],"Europe": ['Germany','UK']}),同时要把对象中的"United Kingdom"替换为"UK"。但运行自己写的代码后,输出错误结果{ Europe: undefined },请帮忙找出问题。

原代码

const arr = [
         {
            'id':1,
            'geography':'region',
            'zone':'Europe',
            'countries':['United Kingdom','France','Germany']
         },
         {
            'id':1,
            'geography':'global',
            'zone':'global',
         },
         {
            'id':1,
            'geography':'region',
            'zone':'Europe',
            'countries':['France','Germany','Netherlands']
         }
        ];
        
const obj = {};

for(let i=0; i<arr.length; i++) {
 //Check if geography is region only
 if(arr[i].geography === 'region') {
    //Checking if property is already exists in object
    if(obj[arr[i].zone]) {
        obj[arr[i].countries].map((items) => {
           obj[arr[i].zone].push(items);     
        });
    }
    //If property is not there then insert
    else{
        obj[arr[i].zone] = obj[arr[i].countries];
    }
  }
}  

console.log(obj);

当前错误输出

{ Europe: undefined }

问题点分析

  • 属性引用完全错误:代码里多次写obj[arr[i].countries],但arr[i].countries是当前项的国家数组,把它当作obj的键来取值,自然找不到对应属性,结果就是undefined。正确的做法是直接使用arr[i].countries访问当前的国家列表,而不是从目标对象obj里取。
  • 数组合并逻辑冗余且错误:用map遍历数组再逐个push完全没必要,而且map的返回值也没用到;另外完全没处理"United Kingdom"替换成"UK"的需求。
  • 未处理重复国家:原代码会把同一国家多次添加(比如France、Germany会出现两次),最终结果会有重复值。

修复后的代码

const arr = [
  {
    'id':1,
    'geography':'region',
    'zone':'Europe',
    'countries':['United Kingdom','France','Germany']
  },
  {
    'id':1,
    'geography':'global',
    'zone':'global',
  },
  {
    'id':1,
    'geography':'region',
    'zone':'Europe',
    'countries':['France','Germany','Netherlands']
  }
];

const obj = {};

for(let i=0; i<arr.length; i++) {
  // 只处理region类型的项
  if(arr[i].geography === 'region') {
    const zone = arr[i].zone;
    // 处理国家名称替换
    const processedCountries = arr[i].countries.map(country => {
      return country === 'United Kingdom' ? 'UK' : country;
    });
    
    if(obj[zone]) {
      // 合并数组并去重
      obj[zone] = [...new Set([...obj[zone], ...processedCountries])];
    } else {
      // 首次创建大洲对应的国家数组
      obj[zone] = [...processedCountries];
    }
  }
}  

console.log(obj);
// 输出:{ Europe: ['UK', 'France', 'Germany', 'Netherlands'] }

修复说明

  1. 修正了属性引用错误,直接使用当前项的countries数组,而非从obj中错误取值。
  2. 添加了国家名称替换逻辑,将"United Kingdom"转为"UK"。
  3. 使用Set对合并后的数组去重,避免重复国家出现。
  4. 用扩展运算符...简化数组合并操作,比逐个push更高效简洁。

内容的提问来源于stack exchange,提问作者Digvijay Singh Thakur

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 00:47:32