Skip to content

Instantly share code, notes, and snippets.

@pepijnolivier
Created November 21, 2018 12:53
Show Gist options
  • Save pepijnolivier/0f1431a0a4805ff53423b416e859f968 to your computer and use it in GitHub Desktop.
Save pepijnolivier/0f1431a0a4805ff53423b416e859f968 to your computer and use it in GitHub Desktop.
Get a nested object value
function returnDefault(defaultReturn) {
return typeof defaultReturn === 'undefined' ? null : defaultReturn;
}
/**
* Usage:
* const obj = { id: 123, name: "John Doe", info: { married: false, partner: { id: 456, name: 'Mary Brown' } } }
* const defaultValue = '/';
* const dotProp = 'info.partner.name'
*
* const nameOfPartner = getDotProp(obj, dotProp, defaultValue);
*
* @param {object} myObject
* @param {string} myDotProp
* @param {*} defaultReturn
*/
function getDotProp(myObject, myDotProp, defaultReturn) {
try {
// 0. Return default on invalid input
if (typeof myDotProp !== 'string' || typeof myObject !== 'object') {
debugger;
return returnDefault(defaultReturn);
}
// 1. Extract the dot property
const dotSplit = myDotProp.split('.');
let dotProp = myObject;
for (let i = 0; i < dotSplit.length; i++) {
const currentProp = dotSplit[i];
dotProp = dotProp[currentProp];
}
// 2. Return the default if dot property was undefined.
// Or in case everything went as expected, return the dot property
return typeof dotProp === 'undefined' ? returnDefault(defaultReturn) : dotProp;
} catch (e) {
return returnDefault(defaultReturn);
}
}
export default getDotProp;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment