Add id to array of objects - Javascript

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);


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; }


You can use the map() function to iterate over your array of objects.

n is each of your objects and you can set the id value inside the map.

Hope this helps :)

let 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"
  }
]

let i = 0;
arr.map(n => {
  n['id'] = i;
  i++;
})

  console.log(arr);