Last active
May 4, 2023 14:22
-
-
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.
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
/** | |
* 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