Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
197
rated 0 times [  199] [ 2]  / answers: 1 / hits: 96816  / 10 Years ago, tue, may 20, 2014, 12:00:00

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 where I can pull out values like myarray[0].Name which would give me Adam.



However, after this array is built, how can I add an address field with a value of somewhere street into the array at position [0], so that my fields in that object at position zero are now Name, Age, and Address with corresponding values?



I was thinking splice() somehow but couldn't find an example using objects, just examples with simple arrays.


More From » arrays

 Answers
23

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 ) );




[#70929] Sunday, May 18, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
chauncey

Total Points: 377
Total Questions: 91
Total Answers: 99

Location: Jordan
Member since Thu, Aug 5, 2021
3 Years ago
;