16

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.

1
  • 2
    Why can't you do myarray[0].address = "somewhere street"? Commented May 20, 2014 at 19:27

2 Answers 2

27

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

Sign up to request clarification or add additional context in comments.

Comments

9

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.