Last active
July 17, 2018 15:55
-
-
Save getanwar/89f568d5612f193d0e8a7340bd1937b6 to your computer and use it in GitHub Desktop.
getPropsChainVal() - returns either the desired value or undefined
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* getPropsChainVal function is helpful when we want to | |
* retrive value from a deep object and properties from | |
* anywhere in the middle can go missing resulting an error. | |
* `TypeError: Cannot read property '...' of undefined` | |
* The function returns either the desired value or undefined | |
* | |
* @param {Object} obj | |
* @param {String} propsChain // 'data.sample.posts.items' | |
* @return value || undefined | |
*/ | |
function getPropsChainVal(obj, propsChain) { | |
if (typeof obj !== 'object' || typeof propsChain !== 'string') { | |
throw new Error('Both args are required as an object and a string respectively'); | |
} | |
propsChain = propsChain.split('.'); | |
return propsChain.reduce((obj, key) => { | |
return typeof obj !== 'object' | |
? undefined | |
: obj[key]; | |
}, obj); | |
} | |
/** | |
* Example | |
*/ | |
const obj = { | |
data: { | |
sample: { | |
posts: { | |
items: [1, 2, 3] | |
} | |
} | |
} | |
}; | |
const items = getPropsChainVal(obj, 'data.sample.posts.items'); | |
console.log(items); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
bah