获取嵌套对象的值

时间:2013-07-12 16:06:52

标签: javascript object arraylist

我有以下对象,我需要检索“地址”字段值。

var south= {};
south.address = {
    "South Building" :{
        address: "7421 New York Avenue",
        address2: "",
        city: "Georgetown",
        state: "DC",
        zip: "10221",
        phone:"202.555.9999",
        fax: "202.555.6696"
    }
};

我目前只能通过以下方式获取该字段的名称:

Object.keys(south.address["South Building"])

返回:["address", "address2", "city", "state", "zip", "phone", "fax"]

Object.keys(south.address["South Building"])[0]

返回:"address"

我想获得“地址”的价值。有人有什么想法吗?

2 个答案:

答案 0 :(得分:0)

您必须使用检索到的密钥:

var key = Object.keys(southland.address["SoCal Accounting"])[0];
var value = southland.address["SoCal Accounting"][key];

对于你的钥匙数组:

var keys = Object.keys(southland.address["SoCal Accounting"]);
for(var i = 0; i < keys.length; i++) {
    var key = keys[i];
    console.log(southland.address["SoCal Accounting"][key]);
}

答案 1 :(得分:0)

我遇到的真正问题是这个对象改变了吗? 如果它没有改变,你可以这样访问地址属性:

south.address["South Building"].address

如果确实发生了变化(我认为"South Building"最有可能发生变化),但整体结构与您在这样的for循环中访问每个“建筑物”的地址相同

for(var building in south.address){
    var address = south.address[building].address;
    //do what you want with address here.
}

如果实际上内部对象的结构发生了变化(即address不是一个gauranteed属性),那么如果它存在,你仍然可以访问它:

for(var building in south.address){
    if("address" in south.address[building]){
       var address = south.address[building].address;
       //do what you want with address here.
    }
}