如何访问JSON兄弟“密钥”?

时间:2014-08-16 15:16:42

标签: javascript jquery json key-value

我有一个json结构,如:

     var abraham = {

                   wife:{
                    name:"Sarah"
                        },

                  first_born:{
                    name: "Isaac"
                    wife:"Rebekkah",
                    child:"Jacob"

                      },

现在我有一个新的"键"我想要它的价值"成为其中一个兄弟姐妹的价值。 Someyhing喜欢:

abraham_first_born_name:  first_born.name, //I get Errors:

我试过了:

abraham_first_born_name:  first_born.name, //Error: first_born.name undefined
abraham_daughter_in_law: first_born.wife, //Error: first_born.wife undefined
abraham_grand_child:     first_born.child,  ////Error: first_born.child undefined

并尝试过:

abraham_first_born_name:  this.first_born.name, //Error: this.first_born.name undefined
abraham_daughter_in_law: this.first_born.wife, //Error: this.first_born.wife undefined
abraham_grand_child:     this.first_born.child,  ////Error: this.first_born.child undefined

最后尝试过:

abraham_first_born_name:  $(this).first_born.name, //Error: $(this).first_born.name undefined
abraham_daughter_in_law: $(this).first_born.wife, //Error: $(this).first_born.wife undefined
abraham_grand_child:     $(this).this.first_born.child,  ////Error: $(this).first_born.child undefined    
}

如何访问key数据,例如abraham_first_born_name,将其指定为first_born.name ....的值...兄弟姐妹key' s ??

请注意,在询问此任务之前,我访问了谷歌的小时数并尝试了:How to access Json key inside a json keyjson sibling data以及Getting json sibling dataHow to access key itself using javascript以及Accessing siblings in jquery和{ {3}}

感谢您的任何建议。

2 个答案:

答案 0 :(得分:6)

您必须使用单独的声明:

 var abraham = {

               wife:{
                name:"Sarah"
                    },

              first_born:{
                name: "Isaac"
                wife:"Rebekkah",
                child:"Jacob"

                  }
 };

 abraham.abraham_first_born_name = abraham.first_born.name;

答案 1 :(得分:1)

您可以使用Object.create执行此操作,但这有点冗长。

var abraham = Object.create(Object.prototype, {
    wife: {value: {name: "Sarah"}},
    first_born: {value: {name: "Isaac"}},
    abraham_first_born_name: {
        get: function () {
            return this.first_born.name;
        }
    }
});

http://jsfiddle.net/n4xqbjdo/