Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add id to array of objects

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.

like image 574
a2441918 Avatar asked Apr 25 '18 13:04

a2441918


2 Answers

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);
like image 137
31piy Avatar answered Oct 19 '22 23:10

31piy


  source.map((s, i)=> s.id = i+1); 
   console.log(source)
like image 20
Naim Blg Avatar answered Oct 19 '22 22:10

Naim Blg