将ID添加到对象数组 [英] Add id to array of objects
本文介绍了将ID添加到对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个对象数组.如何从1开始向他们添加ID密钥.
I have an array of objects. How do I add an id key to them starting from 1.
[
{
color: "red",
value: "#f00"
},
{
color: "green",
value: "#0f0"
},
{
color: "blue",
value: "#00f"
},
{
color: "cyan",
value: "#0ff"
},
{
color: "magenta",
value: "#f0f"
},
{
color: "yellow",
value: "#ff0"
},
{
color: "black",
value: "#000"
}
]
所以,就像
[
{
color: "red",
value: "#f00",
id: 1
},
{
color: "green",
value: "#0f0",
id: 2
},
{
color: "blue",
value: "#00f",
id: 3
},
{
color: "cyan",
value: "#0ff",
id: 4
},
{
color: "magenta",
value: "#f0f",
id: 5
},
{
color: "yellow",
value: "#ff0",
id: 6
},
{
color: "black",
value: "#000",
id: 7
}
]
我尝试使用 forEach
,但是它返回了 id
作为长度-数组内所有对象的1值.
I tried using forEach
but it was returning the id
as the length - 1 value for all the objects inside the array.
我有很多对象,也可以使用 lodash
.
I have a large number of objects and can use lodash
too.
推荐答案
const source = [{
color: "red",
value: "#f00"
},
{
color: "green",
value: "#0f0"
},
{
color: "blue",
value: "#00f"
},
{
color: "cyan",
value: "#0ff"
},
{
color: "magenta",
value: "#f0f"
},
{
color: "yellow",
value: "#ff0"
},
{
color: "black",
value: "#000"
}
];
source.forEach((item, i) => {
item.id = i + 1;
});
console.log(source);
这篇关于将ID添加到对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文