【问题标题】:Get javascript object property via key name in variable [duplicate]通过变量中的键名获取javascript对象属性[重复]
【发布时间】:2011-12-19 02:56:58
【问题描述】:

假设我在 javascripts 中有这样的东西:

var obj = {
  subObj : {}
};
var type = 'subObj';

我怎样才能得到obj's subObjtype?例如,我想做类似的事情:

obj.(type);

【问题讨论】:

    标签: javascript


    【解决方案1】:

    obj[type]

    你使用下标符号。

    11.2.1 Property Accessors

    属性通过名称访问,使用点符号:

    MemberExpression . IdentifierName
    CallExpression . IdentifierName
    

    或括号表示法:

    MemberExpression [ Expression ]
    CallExpression [ Expression ]
    

    【讨论】:

      【解决方案2】:

      您可以将对象视为 JavaScript 中的关联数组,因此您可以像这样访问内部对象:

      var obj = {
          subObj : {}
      };
      
      var type = "subObj";
      var subObj = obj[type];
      

      【讨论】:

        【解决方案3】:

        如果有人想知道如何(动态)访问子属性,我已经找到了一种方法,如果有更简单的方法,请告诉我:

        function getPropertyByKeyPath(targetObj, keyPath) { 
          var keys = keyPath.split('.');
          if(keys.length == 0) return undefined; 
          keys = keys.reverse();
          var subObject = targetObj;
          while(keys.length) {
           var k = keys.pop();
           if(!subObject.hasOwnProperty(k)) {
            return undefined;
           } else {
            subObject = subObject[k];
           }
         }
         return subObject;
        }
        

        例如:

              var o = {result : {info:{ version:1, comment: 'test'}}};
              var subObject = getPropertyByKeyPath(o, 'result.info');
              console.log(subObject);
        

        会导致:

        {version: 1, comment: "test"} 
        

        【讨论】:

          【解决方案4】:
          obj[type]
          

          根本没有任何意义 - 你没有访问类型,这些是简单的属性 - 可以通过 obj[keyName] 或类似的方式访问它们,但使用 type 非常令人困惑,并且肯定是缺乏理解的迹象

          【讨论】:

          • 嗯,属性就是类型。如果你“console.log(typeof(obj.subObj));”,它会将“object”返回到标准输出。然而,属性可以通过“obj.subObj”或“obj['subObj']”而不是“obj[subObj]”来访问。后者不起作用,因为括号中的对象名称必须以字符串形式呈现。
          【解决方案5】:
              var obj = {
                subObj : {}
              }
              var type = 'subObj';
          
              console.log(typeof obj.subObj); //will print "object"
              console.log(obj.subObj); //will print "{}"
          
              //You can add a new propery like this:
              obj.subObj.newProperty = 'hello';
              console.log(typeof obj.subObj.newProperty); //will print "string"
              console.log(obj.subObj.newProperty); //will print "hello"
          
              // you can also add new properties like this
              obj.subObj['newProperty'] = 5; // this is very useful if you have to add properties with names that use reserved words or that contain illegal characters.
              console.log(typeof obj.subObj.newProperty); //will print "number"
              console.log(obj.subObj.newProperty); //will print "5"
          
              //In the case where you're using reserved or illegal words you'l have to do this  
              obj.subObj['new/Property'] = 'cat'; // this is very useful if you have to add properties with names that use reserved words or that contain illegal characters.
              console.log(typeof obj.subObj['new/Property']); //will print "number"
              console.log(obj.subObj['new/Property]); //will print "5"
          
              // and add another property in  the chain:
              obj.subObj['new/PropertyGroup']={
          'illegal/name':'value', 
          acceptableName: 5, 
          andotherObject:{},
          'illegally&Named(object)':{} 
          }
          

          【讨论】:

            猜你喜欢
            • 2012-07-15
            • 2014-09-23
            • 2012-12-07
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多