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 .forEach() to iterate over array elements and add id
:
data.forEach((o, i) => o.id = i + 1);
Demo:
let data = [{
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"
}];
data.forEach((o, i) => o.id = i + 1);
console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }