Add id to array of objects - Javascript

后端 未结 8 1754
星月不相逢
星月不相逢 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:17

    The simples solution would be to use map function

    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 = data.map((x, i) => {
      x.id = i + 1
      return x
    })
    
    console.log(data)

提交回复
热议问题