Add id to array of objects - Javascript

后端 未结 8 1752
星月不相逢
星月不相逢 2021-02-15 10:27

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: \"         


        
8条回答
  •  情歌与酒
    2021-02-15 11:20

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

提交回复
热议问题