Javascript 通过变量中的键名获取javascript对象属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8556673/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get javascript object property via key name in variable
提问by Kyle Decot
Say I have something that looks like this in javascripts:
假设我在 javascripts 中有这样的东西:
var obj = {
subObj : {}
};
var type = 'subObj';
How can I get obj's
subObj
w/ type
? For instance I would like to do something like:
我怎样才能得到obj's
subObj
瓦特/ type
?例如,我想做类似的事情:
obj.(type);
回答by Raynos
obj[type]
obj[type]
You use subscript notation.
您使用下标表示法。
11.2.1 Property Accessors
11.2.1 属性访问器
Properties are accessed by name, using either the dot notation:
属性通过名称访问,使用点符号:
MemberExpression . IdentifierName
CallExpression . IdentifierName
or the bracket notation:
或括号表示法:
MemberExpression [ Expression ]
CallExpression [ Expression ]
回答by Jon Newmuis
You can treat objects like associative arrays in JavaScript, so you'll be able to access the inner object like:
你可以像 JavaScript 中的关联数组一样对待对象,这样你就可以像这样访问内部对象:
var obj = {
subObj : {}
};
var type = "subObj";
var subObj = obj[type];
回答by Balance
In case someone was wondering how to access sub properties (dynamically), I have found a way for that, if there's an easier way, please let me know:
如果有人想知道如何(动态)访问子属性,我已经找到了一种方法,如果有更简单的方法,请告诉我:
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;
}
For example this:
例如这个:
var o = {result : {info:{ version:1, comment: 'test'}}};
var subObject = getPropertyByKeyPath(o, 'result.info');
console.log(subObject);
would result in:
会导致:
{version: 1, comment: "test"}
回答by name
obj[type]
doesnt make any sense at all - you're not accessing TYPES, these are simple PROPERTIES - one could access them via obj[keyName]
or something similar but using type
is extremely confusing and a sure sign of lack of understanding
根本没有任何意义 - 你没有访问类型,这些是简单的属性 - 可以通过obj[keyName]
或类似的东西访问它们,但使用type
非常令人困惑,并且是缺乏理解的明确标志
回答by iuppiter
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)':{}
}