Add a Key Value Pair to an array of objects in javascript?

后端 未结 2 1591
走了就别回头了
走了就别回头了 2021-02-05 10:47

If I had an array as such:

var myarray = [];

myarray.push({
    \"Name\": \'Adam\',
    \"Age\": 33
});

myarray.push({
    \"Name\": \'Emily\',
    \"Age\": 32         


        
相关标签:
2条回答
  • 2021-02-05 11:11

    You can simply add properties ("fields") on the fly.

    Try

    myarray[0].Address = "123 Some St.";
    

    or

    myarray[0]["Address"] = "123 Some St.";
    

    var myarray = [];
    
    myarray.push({
        "Name": 'Adam',
        "Age": 33
    });
    
    myarray.push({
        "Name": 'Emily',
        "Age": 32
    });
    
    myarray[0]["Address"] = "123 Some St.";
    
    console.log( JSON.stringify( myarray, null, 2 ) );

    0 讨论(0)
  • 2021-02-05 11:20

    Along with a single value like

    myarray[0].address = "your address";
    

    You could even add a nested property on the fly as below:

    myarray[0].address = { presentAddress: "my present address..." };
    

    and get the value as myarray[0].address.presentAddress;.

    0 讨论(0)
提交回复
热议问题