简体   繁体   English

Javascript:如何向具有键值对的数组中添加新元素?

[英]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. 我有一个数组说a[0] ,它已经有自己的键值对。 Now I'd like to another element to the array a which would be a[1] and add a property to it. 现在,我想将另一个元素添加到数组a中,该元素将为a[1]并为其添加一个属性。

I'd like to add key value pairs to that newly added property to a[1] . 我想将键值对添加到a[1]新添加的属性中。

Ex : a[1] now has say address . 例如: a[1]现在有说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" 然后我想添加另一个键值对,例如“ 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]. 这应该是针对相同的数组索引:a [1]。

How do I do this? 我该怎么做呢?

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

You can use push , using index will may cause unwanted issues, as you need to remember / calculate size of array every-time. 您可以使用push,使用index可能会导致不必要的问题,因为您每次都需要记住/计算数组的大小。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM