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
1

2 Answers 2

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"]
Sign up to request clarification or add additional context in comments.

Comments

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.