Suppose I have this:
var a = { A : { AA : 1 }, B : 2 };
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?
Not directly.
Solution 1 – use object flattening
Flatten object, to have new object
var a = { 'A.AA' : 1; B : 2 };.See compressing object hierarchies in JavaScript
or Flattening a complex json object for mvc binding to get the javascript function for it.
Soution 2 – write key-path accessor
I can see it was already addressed by Eugen.
Reposted code-reviewed version:
Solution 3 – use eval
Be careful with this solution as you may introduce some security issues. It is more of the curiosity.