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.
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);
source.map((s, i)=> s.id = i+1);
console.log(source)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With