Skip to content

Instantly share code, notes, and snippets.

@bhaireshm
Last active May 4, 2023 14:22
Show Gist options
  • Save bhaireshm/facbced02fc8ec04ed00091e76396e1b to your computer and use it in GitHub Desktop.
Save bhaireshm/facbced02fc8ec04ed00091e76396e1b to your computer and use it in GitHub Desktop.
Get nested value from the given object. It checks for the key first then returns the value.
/**
* Get nested value from the given object. It checks for the key first then returns the value.
*
* @param {object} d
* @param {string} k - key name separated by dot character
* @example
* const data = {
pid: 'some-id',
portions: { name: 'section' }
}
* console.log(getNestedValue(data, "portions.name")); // 'section'
*
* @returns value, If nothing found null will be returned.
*/
function getNestedValue(d = {}, k = "") {
const keys = String(k).split(".");
if (!keys.length) return null;
return keys.reduce((p, c) => Object(p).hasOwnProperty(c) ? p[c] : null, d);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment