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

JavaScript按id更新数组元素异常,如何修正map方法实现代码?

JS根据id修改数组元素的实现方案

问题原因

  • 原代码中map遍历未返回元素:map方法要求每轮迭代必须有返回值,否则最终生成的数组元素全为undefined
  • 缺少匹配到对应id后的元素修改逻辑

修正后代码

const items = [
  { id: 1, value: "first" },
  { id: 2, value: "second" },
  { id: 3, value: "third" }
];
const expectedOutput = [
  { id: 1, value: "first" },
  { id: 2, value: "newvalue" },
  { id: 3, value: "third" }
]
function getData(value, id) {
  return items.map((_each)=> {
    // 匹配到对应id时,返回修改后的新对象
    if(_each.id === id) {
      return { ..._each, value }
    }
    // 未匹配到的元素直接返回原对象
    return _each
  })
}

console.log(getData("newvalue", 2))

逻辑说明

  • 用扩展运算符...拷贝原对象的所有属性,再覆盖value属性,避免直接修改原数组内的对象,保证函数无副作用
  • 每轮遍历都明确返回值,最终输出结果和expectedOutput完全一致

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 13:57:03