Add id to array of objects - Javascript

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

    when i use this solutions my ids get one number like this:

    list = [ {
        color: "red",
        value: "#f00",
        id: 0
    }, {
    
        color: "green",
        value: "#0f0",
        id: 4
    },{
        color: "blue",
        value: "#00f",
        id: 4
    },{
        color: "cyan",
        value: "#0ff",
        id: 4
    },{
        color: "black",
        value: "#000",
        id: 4
    }] 
    

    my code is this:

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

提交回复
热议问题