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 could use Array#forEach for this. The second argument of the callback refers to the index of the element. So you can assign the ID as index + 1
.
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);