0

Silly example:

<script>
var a = {
    'b' : {
        'c' : "success!!"
    }
};
var d = 'b.c';
</script>

How could I access success!! if I can't go for the obvious solution a.b.c or a['b']['c'], but instead have to use d? I tried a[d], which doesn't seem to do the trick. I also tried to fiddle with eval(). Is this even possible?

Oliver M.
  • 61
  • 1
  • 7

2 Answers2

1

Try splitting

var a = {
    'b' : {
        'c' : "success!!"
    }
};
var d = 'b.c';

var splat = d.split('.');

console.log(a[splat[0]][splat[1]]);
AmmarCSE
  • 30,079
  • 5
  • 45
  • 53
1

If it's really necessary to have the keys in a string separated with a dot, I would use split and reduce:

var success = d.split(".").reduce(function (obj, key) {
  return obj[key];
}, a);
Razem
  • 1,421
  • 11
  • 14