Aravind S
Aravind S

Reputation: 535

Javascript : how to add a new element to the array that has key value pairs?

I have an array say a[0] which already has it's own key value pairs. Now I'd like to another element to the array a which would be a[1] and add a property to it.

I'd like to add key value pairs to that newly added property to a[1].

Ex : a[1] now has say address. Now I want to add key value pairs such as

"street" : "Avenue St"
"pin" : "560064"

And then I want to add another key-value pair say "city" : "Tokyo"

Finally it must look like :

address : {
   "street" : "Avenue St"
   "pin" : "560064"
}
city : "Tokyo"

And this should be for the same array index : a[1].

How do I do this?

Upvotes: 0

Views: 61

Answers (2)

Atul Sharma
Atul Sharma

Reputation: 10655

You can use push , using index will may cause unwanted issues, as you need to remember / calculate size of array every-time.

var a = [{name: "John"}];
a.push({ address: {"street" : "Avenue St", "pin" : "560064"} });

console.log(a);

Upvotes: 1

Mamun
Mamun

Reputation: 68933

You can do the following way:

var a = [{name: "John"},{address: "Old Avenue St"}];
a[1].address = {"street" : "Avenue St", "pin" : "560064"};

console.log(a);

Upvotes: 1

Related Questions