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
asked Jul 9, 2015 at 17:35
Get Off My Lawn
36.6k47 gold badges201 silver badges381 bronze badges
1 Answer 1
You're almost there. This code will give you what you want:
console.log(deep_value(obj, 'foo.bar.animals.1.name')); // Should show "Bob"
Edit: If you still want to use the [1] syntax for array, here is an alternative version (split the path by ., [ and ]:
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++){
if (path[i]){
obj = obj[path[i]];
}
};
return obj;
};
console.log(deep_value(obj, 'foo.bar.animals[1].name')); // Should show "Bob"
answered Jul 9, 2015 at 17:38
Tuan Anh Hoang-Vu
2,0151 gold badge22 silver badges32 bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
Get Off My Lawn
never thought of that... I do like the
[1] version though because then we know that it is an array... Is it at all possible for that syntax?Brent Echols
you could extend the language to also parse an array index, and simply use a regex to match [^[[]+]. That way you can pull out what you are indexing, and simply go about your business the same way as before.
Get Off My Lawn
That is awesome! works like a charm, and supports deep arrays! This works too:
foo.bar.animals[0].colors[1]. Thank you very much!lang-js