Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
115 views
in Technique[技术] by (71.8m points)

javascript - Parse object dot notation to retrieve a value of an object

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

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...