Add a pair of key values ​​to an array of objects in javascript?

If I had an array as such:

var myarray = []; myarray.push({ "Name": 'Adam', "Age": 33 }); myarray.push({ "Name": 'Emily', "Age": 32 }); 

This gives me an array in which I can pull out values, such as myarray[0].Name , which will give me "Adam".

However, after creating this array, how can I add the “address” field with the value “somewhere” to the array at position [0], so now my fields in this object are at position zero Name , Age and Address with the corresponding values ​​<

I somehow thought splice() , but could not find an example using objects, just examples with simple arrays.

+6
source share
2 answers

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 ) ); 
+16
source

along with one value, for example

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

Even you can add a nested property on the fly, as shown below:

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

and can get a value like: myarray[0].address.presentAddress;

thanks

+4
source

Source: https://habr.com/ru/post/969603/


All Articles