I found this code (https://stackoverflow.com/a/8817473/1778465), which works nicely, but when I want to get a value from an array such as item 1 I get undefined
, I am not really sure what I can do to get array items as well. Any ideas?
This is the code:
var obj = {
foo: { bar: {animals: [{name: "Billy"},{name: "Bob"},{name: "Joe"}]}}
};
var deep_value = function(obj, path){
for (var i=0, path=path.split('.'), len=path.length; i<len; i++){
obj = obj[path[i]];
};
return obj;
};
console.log(deep_value(obj, 'foo.bar.animals[1].name')); // Should show "Bob"
The above gives me the following error:
Uncaught TypeError: Cannot read property 'name' of undefined