通过变量中的键名获取 javascript 对象属性

Get javascript object property via key name in variable

本文关键字:获取 javascript 对象 属性 变量      更新时间:2023-09-26

假设我在javascripts中看起来像这样:

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

我怎样才能获得obj's subObj type?例如,我想做这样的事情:

obj.(type);

obj[type]

使用下标表示法。

11.2.1 属性访问器

属性按名称访问,使用点表示法之一:

MemberExpression . IdentifierName
CallExpression . IdentifierName

或括号表示法:

MemberExpression [ Expression ]
CallExpression [ Expression ]

您可以在 JavaScript 中将对象视为关联数组,因此您将能够访问内部对象,如下所示:

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

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

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"} 
obj[type]

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

    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)':{} 
}