Add id to array of objects - Javascript

后端 未结 8 1759
星月不相逢
星月不相逢 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条回答
  •  -上瘾入骨i
    2021-02-15 11:22

    ES6

    You can use forEach() to get the required result.

    const 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"}];
    
    arr.forEach((o,i)=>o.id=i+1);
    console.log(arr);
    .as-console-wrapper {max-height: 100% !important;top: 0;}

    You can also use map() to get the required result.

    DEMO

    const 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"}];
    
    
    console.log(arr.map((o,i)=>Object.assign(o,{id:i+1})));
    .as-console-wrapper {max-height: 100% !important;top: 0;}

提交回复
热议问题