将变量与嵌套Javascript对象一起使用 [英] Using variables with nested Javascript object
问题描述
假设我有这个:
var a = { A : { AA : 1 }, B : 2 };
我是否可以创建一个变量,使我可以引用AA或B?语法是什么样的?
Is there a way for me to create a variable that could allow me to reference either AA or B? What would the syntax look like?
// I know I can do this:
a['B']; // 2
a['A']['AA']; // 1
// something like this?
var myRef = ???;
a[myRef]; 1 or 2 depending on myRef
如果没有,那么在这里得到我想要的东西的更好的方法是什么?
If not, what's a better way to get what I'm going for here?
推荐答案
不直接.
平对象,具有新对象 var a = {'A.AA':1;B:2};
.
请参见在JavaScript中压缩对象层次结构或将复杂的json对象平铺以进行mvc绑定以获取的javascript函数.
See compressing object hierarchies in JavaScript or Flattening a complex json object for mvc binding to get the javascript function for it.
我看到Eugen已经解决了它.重新发布了经过代码审查的版本:
I can see it was already addressed by Eugen. Reposted code-reviewed version:
function Leaf(obj,path) {
path=path.split('.');
var res=obj;
for (var i=0;i<path.length;i++) res=res[path[i]];
return res;
}
解决方案3-使用eval
var x = eval("a." + myRef); // x will be 1 for myRef == "A.AA", 2 for "B"
请谨慎使用此解决方案,因为您可能会引入一些安全问题.这更多的是好奇心.
Be careful with this solution as you may introduce some security issues. It is more of the curiosity.
这篇关于将变量与嵌套Javascript对象一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!