以下内容应该推出" Yuval"
console.log(pathFind(["book", "author", "name"], {
book: {
author: {
name: "Yuval"
}
}
}));
我已尝试编写此功能,但不断返回undefined
:
function pathFind(path, object) {
return path.reduce((accumulator, name) => {
if(accumulator && accumulator[name] != typeof 'object') {
accumulator[name]
} else {
undefined, object
}
})
}
我错过了什么? (一个错字?)
有没有办法在此函数中结合使用递归? (即如何为此进行递归?)
答案 0 :(得分:0)
尝试以下方法:
var obj = {
book: {
author: {
name: "Yuval"
}
}
};
var path = ["book", "author", "name"];
function findPath(obj, path){
if(path.length === 0) return obj;
return findPath(obj[path[0]], path.slice(1));
}
console.log(findPath(obj,path));