我有下面的对象数组。如果我做一个console.log,我会看到这个
[Object, Object, Object]
0:Object
name: "Rick"
Contact: "Yes"
1:Object
name:"Anjie"
Contact:"No"
2:Object
name:"dillan"
Contact:"Maybe"
我想要像这样更新上面的对象数组。
[Object, Object, Object]
0:Object
name: "Rick"
Contact: "Yes"
id: 1
1:Object
name:"Anjie"
Contact:"No"
id: 2
2:Object
name:"dillan"
Contact:"Maybe"
id:3
如您所见,我添加了id,只要有新对象,它就会自动递增。
有人可以让我知道如何动态地执行此操作吗?
答案 0 :(得分:1)
实际上非常简单。你可以这样做:
var objs = [{
name: "Rick",
Contact: "Yes"
}, {
name: "Anjie",
Contact: "No"
}, {
name: "dillan",
Contact: "Maybe"
}];
objs.forEach(function(obj, index) {
obj.id = index + 1;
});
console.log(objs);
对于objs
数组中的每个对象,它会添加一个id
,其值为index
(+1因为索引从0开始)