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

遍历对象并依据字典映射更新属性时遇索引错误,求正确方案?

解决属性映射时的索引错误问题

问题根源

你的代码出现索引错误,主要有两个原因:

  • 若example中对应字段的值不是字符串类型(比如数字),而dictionary里的键是字符串,会因键类型不匹配找不到对应值,触发访问错误。
  • 未做边界校验:如果example的字段值在dictionary的对应映射表中不存在,直接访问dictionary[field][example[field]]会抛出Cannot read properties of undefined错误。

修正后的代码

for (const field of Object.keys(dictionary)) {
  // 确认example存在当前字段
  if (field in example) {
    const value = String(example[field]); // 统一转为字符串,匹配字典的键类型
    // 检查映射表中是否存在该键,避免索引错误
    if (dictionary[field].hasOwnProperty(value)) {
      example[field] = dictionary[field][value];
    }
  }
}

代码说明

  1. 类型统一:用String()把example的字段值转为字符串,确保和dictionary里的字符串键匹配(比如example.d是数字1时,也能正确匹配字典里的"1")。
  2. 边界校验:用hasOwnProperty()检查映射表中是否存在对应键,避免访问不存在的属性导致错误。
  3. 高效赋值:直接给example[field]赋值比Object.assign更简洁高效,效果完全一致。

测试验证

用你提供的示例数据运行修正后的代码,会得到预期结果:

const example = {
  a: "foo",
  b: "bar",
  c: 123,
  d: "1",
  e: "3",
  f: false,
};
const dictionary = {
  d:{
    "1": "good",
    "2": "bad",
    "3": "perfect",
    "4": "terrible",
  },
  e:{
    "1": "big",
    "2": "small",
    "3": "huge",
  },
};

// 运行修正后的代码后
console.log(example);
// 输出:{ a: 'foo', b: 'bar', c: 123, d: 'good', e: 'huge', f: false }

内容的提问来源于stack exchange,提问作者DaniloMourelle

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 21:22:42