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

JavaScript中如何根据指定对象键名修改对象数组的对应键?

问题原因分析
  • Array.prototype.forEach() 本身没有返回值,你在map回调中直接返回forEach的执行结果,最终得到的result会是全undefined的数组
  • 没有建立正确的新旧键名映射,也没有保留原有对象的其他属性
  • 现有写法只尝试赋值name对应的值,没有处理amt字段的替换逻辑
正确实现代码

如果你明确知道新旧键名的对应关系,可以直接用映射表实现:

// 定义映射规则:旧键名 => 新键名
const keyMap = {
  name: 'topic',
  amt: 'price'
}

const result = arrobj.data.map(item => {
  // 浅拷贝原对象,保留id、city等不需要修改的属性
  const newItem = {...item}
  // 遍历映射规则替换键名
  Object.entries(keyMap).forEach(([oldKey, newKey]) => {
    newItem[newKey] = newItem[oldKey]
    delete newItem[oldKey]
  })
  return newItem
})

如果你需要直接从obj.data.config中取新键名,不需要手动写映射表,可以用这个版本:

// 从参考对象中取新键名,按顺序对应name、amt两个旧键
const newKeys = Object.keys(obj.data.config)
const oldKeys = ['name', 'amt']

const result = arrobj.data.map(item => {
  const newItem = {...item}
  oldKeys.forEach((oldKey, index) => {
    const newKey = newKeys[index]
    newItem[newKey] = newItem[oldKey]
    delete newItem[oldKey]
  })
  return newItem
})
输出验证

执行上述代码后,result的输出完全符合你的预期:

[
  { id: 1, topic: 'abc', price: '50', city: 'TH' },
  { id: 2, topic: 'zen', price: '100', city: 'IN' }
]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 01:06:00