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: \"
No need for complex function and logic. Simply loop it over forEach
which will also give you the index of each object in the array and assign that index+1
value to the id
property of the object.
var 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"
}
];
arr.forEach((item, index)=>{
item.id = index+1;
});
console.log(arr);