简体   繁体   English

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

[英]Accessing properties of a variable object with JavaScript

I have a js object that looks like this: 我有一个看起来像这样的js对象:

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

I want to access the property listed under the nested object "ocd-division/country:us" (aka "name"), but the problem I'm having is that "ocd-division/country" is a variable object. 我想访问嵌套对象"ocd-division/country:us" (又名“name”)下列出的属性,但我遇到的问题是"ocd-division/country"是一个变量对象。 Like it might be ":can" for Canada or something. 就像加拿大或其他东西可能是“:can”。

My question is, can I still access the name property under that object even though it's variable? 我的问题是,即使它是变量,我仍然可以访问该对象下的name属性吗? I wrote the code I came up with below, but it calls the object literally, so it can't account for a change in the object's name. 我编写了下面提到的代码,但是它按字面意思调用了对象,所以它无法解释对象名称的变化。

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

I'm new to JavaScript so I'm sorry if this is a dumb question. 我是JavaScript的新手,所以如果这是一个愚蠢的问题,我很抱歉。

When you don't know the properties of an object, you can use 当您不知道对象的属性时,您可以使用

  • for...in loop for...in循环

    It iterates enumerable own and enumerable inherited properties. 它迭代可枚举的自有和可枚举的继承属性。

  • Object.keys

    It returns an array which contains enumerable own properties. 它返回一个包含可枚举的自有属性的数组。

  • Object.getOwnPropertyNames

    It returns an array which contains own properties. 它返回一个包含自己属性的数组。

 // 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> 

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

Sure... 当然...

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

If the object has prototype methods you will want to use Object.prototype.hasOwnProperty() to ensure they don't get iterated like so: 如果对象具有原型方法,您将需要使用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
}

Or use Object.keys() if you don't care about IE8 support and iterate over those. 如果您不关心IE8支持并迭代这些,请使用Object.keys()

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

EDIT: Upon re-reading your question it occurs to me that you may already know the key name but want to access the object with a variable key name, which is also absolutely fine: 编辑:重新阅读你的问题后,我发现你可能已经知道密钥名称,但想要使用变量密钥名称访问该对象,这也是绝对正常的:

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

When using [] bracket notation to access an object you can insert any code that evaluates to a string, you could even call a function in there that returns a string. 当使用[]括号表示法访问对象时,您可以插入任何评估为字符串的代码,您甚至可以调用返回字符串的函数。

See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors 请参阅: https//developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors

You can iterate through object using for loop. 您可以使用for循环遍历对象。

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

Here is the for loop 这是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

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

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