The following should put out "Yuval"
console.log(pathFind(["book", "author", "name"], {
book: {
author: {
name: "Yuval"
}
}
}));
I've tried writing this function but it keeps returning undefined
:
function pathFind(path, object) {
return path.reduce((accumulator, name) => {
if(accumulator && accumulator[name] != typeof 'object') {
accumulator[name]
} else {
undefined, object
}
})
}
What am I missing? (a typo?)
Is there a way to use recursion inside this function in combination with reduce? (ie how to approach recursion for this?)
Try the following:
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));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.