简体   繁体   English

向现有的javascript对象添加对象

[英]adding objects to an already existing javascript object

I have a javascript object that contains addresses as follows 我有一个包含以下地址的javascript对象

var addressList = [
    {"AddressID":"10011","AddressType":"Delivery","AddressLine1":"4 Caerleon Drive","AddressLine2":"Bittern","AddressLine3":"","CityTown":"Southampton","County":"Hampshire","PostCode":"SO19 5LF","Country":"United Kingdom","ContactID":"10011"},
    {"AddressID":"10012","AddressType":"Home","AddressLine1":"526 Butts Road","AddressLine2":"Sholing","AddressLine3":"","CityTown":"Southampton","County":"Hampshire","PostCode":"SO19 1DJ","Country":"England","ContactID":"10011"}
]

I want to add another "address" to it so i have somthing like the following 我想添加另一个“地址”,所以我有以下内容

[
{"AddressID":"10011","AddressType":"Delivery","AddressLine1":"4 Caerleon Drive","AddressLine2":"Bittern","AddressLine3":"","CityTown":"Southampton","County":"Hampshire","PostCode":"SO19 5LF","Country":"United Kingdom","ContactID":"10011"},
{"AddressID":"10012","AddressType":"Home","AddressLine1":"526 Butts Road","AddressLine2":"Sholing","AddressLine3":"","CityTown":"Southampton","County":"Hampshire","PostCode":"SO19 1DJ","Country":"England","ContactID":"10011"},
{"AddressID":"10013","AddressType":"Home","AddressLine1":"5436 Bfds Road","AddressLine2":"Sherly","AddressLine3":"","CityTown":"Southampton","County":"Hampshire","PostCode":"SO19 1DJ","Country":"England","ContactID":"10011"}
]

i cant figure out how to do this ? 我不知道该怎么做?

使用Array#push将新对象添加到数组中:

addressList.push({"AddressID":"10013","AddressType":"Home","AddressLine1":"5436 Bfds Road","AddressLine2":"Sherly","AddressLine3":"","CityTown":"Southampton","County":"Hampshire","PostCode":"SO19 1DJ","Country":"England","ContactID":"10011"});

It's not clear to me what you're encountering, but the probable problem you're running into is that the first snippet you give is a javascript Object, and the second snippet is an Array. 我不清楚您遇到了什么,但是您遇到的可能问题是您提供的第一个代码段是一个javascript对象,第二个代码段是一个数组。 You'd need to so something like: 您需要这样的事情:

var addressList = [];
addressList.push({"AddressID":"10011",...});

You could then iterate over the list using a forEach: 然后,您可以使用forEach遍历列表:

addressList.forEach(function(address) {
    alert(address.AddressID);
    doSomethingWithAddress(address);
});

You can read more about Arrays on the MDN 您可以在MDN上阅读有关数组的更多信息

addressList.push({AddressID:1234,Country:'Foo',...});

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

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