Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm finding myself struggling with a little problem. Let's say I've got an object:

var foo = {
    bar: {
        baz: true
    }
};

Now I also have a String 'foo.bar.baz'. I'd now like to retrieve the value from the object using the string.

Please note: This is just an example, the solution needs to be dynamic.

Update:

I need the variable name also to be dynamic and parsed from the string. Also I can't be sure that my variable is a property of the window.

I have already built a solution using eval, but this is pretty ugly I think: http://jsfiddle.net/vvzyX/

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
111 views
Welcome To Ask or Share your Answers For Others

1 Answer

For example,

function get(obj, path) {
    return path.split('.').reduce(function(obj, p) {
        return obj[p]
    }, obj);
}

Demo:

tree = {
    foo: {
        bar: 1,
        baz: { quux: 3 },
    },
    spam: 1
}

console.log(get(tree, 'foo.baz.quux')) // 3

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...