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

如何为数组中的每个对象添加计算得到的new_value属性?

为数组对象添加计算后的新键的解决方案

你之前的代码存在两个关键问题:

  • forEach 里定义的 new_value 是局部变量,外部无法访问;
  • 使用 map 时直接返回 new_value,会让数组变成仅包含计算值的数组,丢失原对象的所有键值。

下面是两种可行的解决方案:

方案一:直接修改原数组对象(forEach)

这种方式会直接给原数组中的每个对象添加新键:

const array = [{A: 5, B:10, C: 20},{A: 3, B: 2, C: 5}];

array.forEach(element => {
  const new_value = (element.A + element.B) / element.C;
  element.new_value = new_value; // 为当前对象新增键值对
});

console.log(array);
// 输出结果:
// [{A: 5, B:10, C: 20, new_value: 0.75},{A: 3, B: 2, C: 5, new_value: 1.2}]

方案二:生成新数组(map,推荐纯函数写法)

这种方式不会修改原数组,而是返回包含新键的新对象数组,更符合函数式编程的理念:

const array = [{A: 5, B:10, C: 20},{A: 3, B: 2, C: 5}];

const updatedArray = array.map(element => {
  const new_value = (element.A + element.B) / element.C;
  // 解构原对象,同时添加新键值对,返回新对象
  return { ...element, new_value };
});

console.log(updatedArray);
// 输出结果:
// [{A: 5, B:10, C: 20, new_value: 0.75},{A: 3, B: 2, C: 5, new_value: 1.2}]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 00:54:55