Javascript: Get deep value from object by passing path to it as string [duplicate]
Possible Duplicate:
Accessing nested JavaScript objects with string key
Maybe the title is not clear enough, I just didn't know how to specify what I'm looking for and my English is really bad, sorry.
I'm trying to create function that returns object value, but also plays nice with nested objects. For example:
var obj = {
foo: { bar: 'baz' }
};
I want to access the value of obj.foo.bar by suppling the string "foo.bar" to the function.
function(obj, path) {
// Path can be "foo.bar", or just "foo".
}
Thanks!
This works correctly:
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;
};
Here is the proof / demo: jsfiddle.net/tadeck/5Pt2q/13/
EDIT: I have removed redundant variables, shortened the code.
Consider this:
var obj = {
foo: { bar: 'baz' }
};
function deepFind(obj, path) {
var paths = path.split('.')
, current = obj
, i;
for (i = 0; i < paths.length; ++i) {
if (current[paths[i]] == undefined) {
return undefined;
} else {
current = current[paths[i]];
}
}
return current;
}
console.log(deepFind(obj, 'foo.bar'))