Skip to content

Instantly share code, notes, and snippets.

@getanwar
Last active July 17, 2018 15:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save getanwar/89f568d5612f193d0e8a7340bd1937b6 to your computer and use it in GitHub Desktop.
Save getanwar/89f568d5612f193d0e8a7340bd1937b6 to your computer and use it in GitHub Desktop.
getPropsChainVal() - returns either the desired value or undefined
/**
* 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);
@hbshifat
Copy link

bah

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment