使用JavaScript访问变量对象的属性

时间:2015-07-11 18:17:10

标签: javascript

我有一个看起来像这样的js对象:

 var object = {
      "divisions": {
          "ocd-division/country:us": {
              "name": "United States",
          }
      }
    };

我想访问嵌套对象"ocd-division/country:us"(又名“name”)下列出的属性,但我遇到的问题是"ocd-division/country"是一个变量对象。就像加拿大或其他东西可能是“:can”。

我的问题是,即使它是变量,我仍然可以访问该对象下的name属性吗?我编写了下面提到的代码,但是它按字面意思调用了对象,所以它无法解释对象名称的变化。

    var country = document.getElementById("p");
    p.innerHTML = object.divisions["ocd-division/country:us"].name;

我是JavaScript的新手,所以如果这是一个愚蠢的问题,我很抱歉。

4 个答案:

答案 0 :(得分:7)

如果您不知道对象的属性,可以使用

// Adding properties: "ownEnumerable", "ownNonEnumerable",
// "inheritedEnumerable" and "inheritedNonEnumerable"
var obj = Object.defineProperties({}, {
  ownEnumerable: {enumerable: true},
  ownNonEnumerable: {},
});
Object.defineProperties(Object.prototype, {
  inheritedEnumerable: {enumerable: true},
  inheritedNonEnumerable: {},
});

// Display results
function log(id, arr) {
  document.getElementById(id).textContent = '[' + arr.join(', ') + ']';
}
log('forin', function(forInProps){
  for (var prop in obj) forInProps.push(prop);
  return forInProps;
}([]));
log('keys', Object.keys(obj));
log('names', Object.getOwnPropertyNames(obj));
<dl>
  <dt><code>for...in</code></dt><dd id="forin"></dd>
  <dt><code>Object.keys</code></dt><dd id="keys"></dd>
  <dt><code>Object.getOwnPropertyNames</code></dt><dd id="names"></dd>
</dl>

答案 1 :(得分:2)

object.divisions[Object.keys(object.divisions)[0]].name

答案 2 :(得分:1)

...不确定

for (var division in object.divisions) {
    var name = object.divisions[division].name;
    // Do what you want with name here
}

如果对象具有原型方法,您将需要使用Object.prototype.hasOwnProperty()来确保它们不会像这样迭代:

for (var division in object.divisions) {
    if (!object.divisions.hasOwnProperty(division)) continue;
    var name = object.divisions[division].name;
    // Do what you want with name here
}

如果您不关心IE8支持并使用Object.keys()进行迭代,请使用https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors

Object.keys(object.divisions).forEach(function(division) {
    var name = object.divisions[division].name;
    // Do what you want with name here
});

编辑:在重新阅读您的问题后,我发现您可能已经知道了密钥名称但想要使用变量密钥名称访问该对象,这也绝对没问题:

var division = 'ocd-division/country:us';
object.divisions[division].name;

使用[]括号表示法访问对象时,可以插入任何求值为字符串的代码,甚至可以调用返回字符串的函数。

请参阅:{{3}}

答案 3 :(得分:1)

您可以使用for循环遍历对象。

var obj = {
    "divisions":{
      "ocd-division/country:us":{
         "name" : "United States"
      }
    }
}

这是for循环

for(var a in obj){ //loop first the object
  for(var b in obj[a]){ // then second object (divisions)
    for(var c in obj[a][b]){ //then third object (ocd-division/country:us)
      if(c == 'name'){ //c is the key of the object which is name
        console.log(obj[a][b][c]); //print in console the value of name which is United States.
        obj[a][b][c] = "Canada"; //replace the value of name.
        var objName = obj[a][b][c]; //or pass it on variable. 
      }
    }
  }
}

console.log(obj); //name: Canada
console.log(objName); //name: United States

You can also use this reference:
https://developer.mozilla.org/enUS/docs/Web/JavaScript/Reference/Statements/for
http://stackoverflow.com/questions/8312459/iterate-through-object-properties