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"
}
]
So, it will be like
[
{
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
}
]
I tried using forEach
but it was returning the id
as the length - 1 value for all the objects inside the array.
I have a large number of objects and can use lodash
too.