Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a Key Value Pair 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 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.

like image 994
jensanity5000 Avatar asked May 20 '14 19:05

jensanity5000


1 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 ) );
like image 192
Paul Roub Avatar answered Oct 06 '22 00:10

Paul Roub