如何访问嵌套对象的值

时间:2019-04-03 16:35:41

标签: javascript object

var allowed_ids = {
            332438809: "Bereznyak24",
            about: {
                address: "Gorky 84",
                average_sum: 50
            },
            489485425: "Bereznyak25",
            about: {
                address: "Sohnstr 41",
                average_sum: 100
            }
        };


var checked = childs[0].innerHTML.replace(/\D+/g, "");
console.log(allowed_ids.checked.about.address);

`

在检查的变量中,我存储了332438809或489485425。说allowed_ids[checked]会导致Bereznyak24或Bereznyak25。但是如何访问addressaverage_sum的值呢? allowed_ids.checked.about.address这一段代码是错误的,不会导致正确的响应。谢谢!

4 个答案:

答案 0 :(得分:1)

allowed_ids必须是一个数组,否则您每次分配about密钥时都会覆盖它。

var allowed_ids = [
{
  332438809: "Bereznyak24",
  about: {
    address: "Gorky 84",
    average_sum: 50
  }
},
{
  489485425: "Bereznyak25",
  about: {
    address: "Sohnstr 41",
    average_sum: 100
  }
}];


var checked = childs[0].innerHTML.replace(/\D+/g, "");
console.log(allowed_ids[checked].about.address);

答案 1 :(得分:1)

您的对象不正确。您应该使用332438809,489485425作为键,并将"Bereznyak24","Bereznyak25"存储为嵌套对象的属性。并使用Bracket Notation访问动态属性名称

var allowed_ids = {
            332438809:{
              name:"Bereznyak24",
              address: "Gorky 84",
              average_sum: 50
            },
            489485425:{
                name:"Bereznyak25",
                address: "Sohnstr 41",
                average_sum: 100
            }
        };


var checked = '332438809';
console.log(allowed_ids[checked].address);
console.log(allowed_ids[checked].name);
console.log(allowed_ids[checked].average_sum);

答案 2 :(得分:1)

您的对象具有重复的键。最好像这样存储它:

var allowed_ids = {
            332438809:{
             name: "Bereznyak24",
             about: {
                address: "Gorky 84",
                average_sum: 50
              }
            },
            489485425: {
             name:  "Bereznyak25",
             about: {
                address: "Sohnstr 41",
                average_sum: 100
             }
           }
        };
// Assuming checked = 489485425
console.log(allowed_ids[checked].about.address)
// Result = Sohnstr 41

答案 3 :(得分:0)

假设您的密钥为489485425和332438809,则可以执行以下操作。

var allowed_ids = {
            332438809: {
                name: "Bereznyak24",
                address: "Gorky 84",
                average_sum: 50
            },
            489485425: {
                name: "Bereznyak25",
                address: "Sohnstr 41",
                average_sum: 100
            }
        };
        
        
        console.log(allowed_ids[489485425].name);
        console.log(allowed_ids[489485425].address);
        console.log(allowed_ids[489485425].average_sum);