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

1 Answer 1

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

3 Comments

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?
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.
That is awesome! works like a charm, and supports deep arrays! This works too: foo.bar.animals[0].colors[1]. Thank you very much!

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.