通过变量中的键名获取 javascript 对象属性
Get javascript object property via key name in variable
假设我在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)':{}
}
相关文章:
- 从ajax请求中获取javascript对象
- 以同步方式获取Javascript Promise的值
- 获取javascript中的公钥格式
- 获取javascript函数中的按钮名称
- 如何在C#中获取Javascript变量值
- 从其名称获取javascript数组对象
- 如何从Selenium获取JavaScript值
- 如何获取javascript输入并在html中调用它
- 获取javascript函数中另一个javascript函数的响应
- 获取javascript中输入元素的索引
- 获取javascript中json_encoded数组的元素
- 在ajax请求中使用jquery获取javascript响应UJS
- 获取Javascript中单选按钮的true或false
- 获取javascript中的元数据属性
- 获取Javascript中DOM元素的screenX
- 如何在事件处理程序中获取 javascript 事件对象
- 使用 JQuery 从表单中获取 javascript 多维数组
- 获取 JavaScript 中复选框的值
- 如何从函数名称中获取JavaScript的源代码
- VBA中有没有一种方法可以获取javascript生成的元素