我正在尝试创建返回对象值的函数,但也可以很好地处理嵌套对象。例如:
var obj = { foo: { bar: 'baz' } };
我想通过向函数提供字符串“ foo.bar”来访问obj.foo.bar的值。
function(obj, path) { // Path can be "foo.bar", or just "foo". }
谢谢!
考虑一下:
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'))