3

I'm trying to access to the hello value through a string (key) I got undefined. I'm out of idea to make it works.

var key = "a.b.c.0";
var test = {"a":{"b":{"c":["hello","world"]}}};
console.log(test[key]); // undefined

console.log(test["a.b.c.0"]); // undefined
console.log(test["a.b.c[0]"]); // undefined
console.log(test["a.b.c"]); // fail
console.log(test.a.b.c); // [ 'hello', 'world' ]
console.log(test.a.b.c[0]); // hello
rootio
  • 33
  • 2

2 Answers2

3

You can do something like this, but not sure how far it'll get you:

key.split('.').reduce(function(test, prop) {
  return test[prop];
}, test);

Examples

'a.b.c.0'.split('.').reduce(function(test, prop) {...
// => "hello"

'a.b.c'.split('.').reduce(function(test, prop) {...
// => ["hello", "world"]
Hunan Rostomyan
  • 2,176
  • 2
  • 22
  • 31
0

If you willing to use a library I highly recommend checking out lodash. For this you can use lodash's get method https://lodash.com/docs#get

_.get(test, key);

Or if you need a basic native JS implementation from Access object child properties using a dot notation string

function getDescendantProp(obj, desc) {
    var arr = desc.split(".");
    while(arr.length && (obj = obj[arr.shift()]));
    return obj;
}

console.log(getDescendantProp(test, key));
//-> hello

another possible way ( I don't recommend it but it should work) is to use eval()

var value = eval('test' + key)
Community
  • 1
  • 1
pwilmot
  • 586
  • 2
  • 8