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: \"
You can use the map()
function to iterate over your array of objects.
n
is each of your objects and you can set the id
value inside the map.
Hope this helps :)
let arr = [{
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"
}
]
let i = 0;
arr.map(n => {
n['id'] = i;
i++;
})
console.log(arr);