Implement lodash get function - kdaisho/Blog GitHub Wiki
We're going to implement lodash get function.
https://lodash.com/docs#get
The function should take path argument as string or array.
(_.get(object, path, [defaultValue]))
It returns default value when an invalid path is given, otherwise it returns the value from the given object.
function myGet(obj, path, defaultValue) {
const pathArray = typeof path === 'string' ? path.split('.') : path
while (pathArray.length) {
obj = obj[pathArray[0]]
if (!obj) {
return defaultValue
}
pathArray.shift()
}
return obj
}
const myObj = {
a: {
b: {
c: 'hello'
}
}
}
// Usage (with string path)
myGet(myObj, 'a.b.c', 'nope') // 'hello'
myGet(myObj, 'a.b', 'nope') // { c: 'hello' }
myGet(myObj, 'a.b.x', 'nope') // 'nope'
// Usage (with array path)
myGet(myObj, ['a','b','c'], 'nope') // 'hello'