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

如何为JavaScript数组中的每个对象添加自增id属性?

为数组对象添加自增id的实现方法

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

如果不需要保留原数组的原始状态,可以用forEach遍历数组,利用索引为每个对象添加自增id:

const arr = [
  {name:'john'},
  {name:'jeff'},
  {name:'bob'},
  {name:'peter'},
]

arr.forEach((item, index) => {
  item.id = index + 1; // 索引从0开始,加1得到从1起始的id
});

console.log(arr);
// 输出结果:[{id:1,name:'john'},{id:2,name:'jeff'},{id:3,name:'bob'},{id:4,name:'peter'}]

方法二:创建新数组(map,不修改原数组)

如果需要保留原数组,推荐用map方法生成新数组,通过展开运算符复制原对象属性并添加id:

const arr = [
  {name:'john'},
  {name:'jeff'},
  {name:'bob'},
  {name:'peter'},
]

const newArr = arr.map((item, index) => ({ ...item, id: index + 1 }));

console.log(newArr); // 目标数组
console.log(arr); // 原数组不受影响

方法三:自定义起始id

如果id不需要从1开始,可以用变量控制起始值:

const arr = [
  {name:'john'},
  {name:'jeff'},
  {name:'bob'},
  {name:'peter'},
]

let startId = 1; // 可自定义起始值
const newArr = arr.map(item => ({ ...item, id: startId++ }));

console.log(newArr);

内容的提问来源于stack exchange,提问作者Nawapol R.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 10:55:28