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
Actually no, because js object are seen as property bags and doing a[X]
is for accessing first level properties only...
But you could wrap the logic a['A']['AA']; // 1
in a function that does the same, like this
//WARN... no undefined check here => todo !
function _(o, path) {
var tmp = o
for (var i=0 ; i < path.length ; i++) {
tmp = tmp[path[i]]
}
return tmp
}
var r = _(a, ['A', 'AA'])
This is pretty much the same as other answers, but the difference is when dummy boy create object property name containing dots... Like var a = {"a.a" : 3 }
is valid.
Now, such problem would occurs maybe more often now with the help of IndexedDB to store anything locally...