0

Let's say I have the following object:

var a = {
    x: {
        y: 'Good job!'
    }
    z: 'Nice try...'
}

and the following strings:

var key1 = "z";
var key2 = "x.y";

Is there a way to access the value of y by using the key2 variable?

console.log(a[key1]) will work because it will get evaled to a['z'], but a[key2] won't because it will get evaled to a['x.y'] which is not valid.

alexandernst
  • 14,352
  • 22
  • 97
  • 197
  • 1
    try console.log(eval('a.' + key2)); – Sohil Desai Feb 19 '14 at 10:51
  • 2
    Have a look at this question, it seems to be what you want: http://stackoverflow.com/questions/8051975/access-object-child-properties-using-a-dot-notation-string?rq=1 – CompuChip Feb 19 '14 at 10:52
  • @SohilDesai will this work only if the object is contained in ```window```? I'm guess yes, right? – alexandernst Feb 19 '14 at 10:57
  • No its not true but its not a good solution check this http://stackoverflow.com/questions/86513/why-is-using-the-javascript-eval-function-a-bad-idea – Sohil Desai Feb 19 '14 at 11:04

0 Answers0