I have JSON that looks like this:
{
"greeting": {
"hello": ["world", "josue", "everybody"]
}
}
I am wondering why I cannot use a string to access it's properties like so:
var str = 'greeting.hello';
var obj = { "greeting": { "hello": ["world", "josue", "everybody"] } };
console.log(obj.str);
The above code logs undefined.
However, if I use eval()
(which I really don't want to...), it works as expected.
var str = 'greeting.hello';
var obj = { "greeting": { "hello": ["world", "josue", "everybody"] } };
console.log(eval('obj.'+str));
That returns ["world", "josue", "everybody"]
.
Why can't I use the first example? Is there a way to access the hello key using a string like shown in the first example (without using eval or modifying the JSON)?