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

如何使用Node.js为JSON数组中的每个对象添加新字段?

给数组对象添加新字段的解决方案

你用push()操作不对是因为它的作用是往数组新增元素,不是修改数组里已有的对象。下面给你两种简单的实现方式:

方法一:直接修改原数组(forEach遍历)

这种方式会直接更新原数组里的每个对象:

const originalArray = [{id:1,data:"test1"},{id:2,data:"test2"}];

// 遍历数组里的每个对象
originalArray.forEach(item => {
  // 根据data字段的值生成type并添加到对象中
  item.type = `${item.data} Type`;
});

console.log(originalArray);
// 输出结果:[{id:1,data:"test1",type: "test1 Type"},{id:2,data:"test2",type: "test2 Type"}]

方法二:生成新数组(map方法,不修改原数组)

如果不想改动原数组,可以用map返回一个包含新对象的数组:

const originalArray = [{id:1,data:"test1"},{id:2,data:"test2"}];

// 遍历原数组,返回带type字段的新对象
const newArray = originalArray.map(item => {
  return {
    ...item, // 复制原对象的所有属性
    type: `${item.data} Type` // 添加新的type字段
  };
});

console.log(newArray);
// 输出结果:[{id:1,data:"test1",type: "test1 Type"},{id:2,data:"test2",type: "test2 Type"}]
console.log(originalArray); // 原数组保持不变

两种方法的区别:

  • forEach直接修改原数组中的对象,适合不需要保留原数据的场景
  • map生成新数组,原数组不受影响,适合需要保留原始数据的场景

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 15:35:26