0

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

Fiddle Found Here

Community
  • 1
  • 1
Get Off My Lawn
  • 34,175
  • 38
  • 176
  • 338

1 Answers1

2

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"
Tuan Anh Hoang-Vu
  • 1,994
  • 1
  • 21
  • 32
  • 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? – Get Off My Lawn Jul 09 '15 at 17:41
  • 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. – Brent Echols Jul 09 '15 at 17:45
  • That is awesome! works like a charm, and supports deep arrays! This works too: `foo.bar.animals[0].colors[1]`. Thank you very much! – Get Off My Lawn Jul 09 '15 at 17:48