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

数组与对象组合场景下执行Filter与Map操作的最优实现方法

实现思路

核心逻辑是做命名格式的转换匹配,步骤如下:

  • 遍历stages数组的每个元素,将元素的key属性从中划线格式转换为下划线格式
  • 用转换后的键名到newData中查找对应的值,存在匹配值就给当前元素添加value属性存储对应值,无匹配则保留原结构即可

代码实现

方式1:直接修改原stages数组

const stages = [
  { key: 'field-one' },
  { key: 'field-two' },
  { key: 'field-three' },
  { key: 'field-four' },
  { key: 'field-five' },
]

const newData = {
  field_four: 9,
  field_five: 'D',
}

stages.forEach(stage => {
  // 中划线转下划线
  const convertedKey = stage.key.replaceAll('-', '_')
  // 校验存在对应值再赋值
  if (Object.prototype.hasOwnProperty.call(newData, convertedKey)) {
    stage.value = newData[convertedKey]
  }
})

执行后stages的输出为:

[
  { key: 'field-one' },
  { key: 'field-two' },
  { key: 'field-three' },
  { key: 'field-four', value: 9 },
  { key: 'field-five', value: 'D' },
]

注:你给出的期望输出里field-four和field-five的value值写反了,属于笔误,上述代码输出为逻辑正确的结果

方式2:不修改原数组,返回新数组

如果不想改动原始的stages数组,可以用map生成新数组:

const processedStages = stages.map(stage => {
  const convertedKey = stage.key.replaceAll('-', '_')
  if (Object.prototype.hasOwnProperty.call(newData, convertedKey)) {
    return { ...stage, value: newData[convertedKey] }
  }
  return { ...stage }
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 12:45:03