Skip to content

Instantly share code, notes, and snippets.

@koalicioous
Created August 3, 2023 00:04
Show Gist options
  • Save koalicioous/004d1116fe7b789b4619683aef1e6aca to your computer and use it in GitHub Desktop.
Save koalicioous/004d1116fe7b789b4619683aef1e6aca to your computer and use it in GitHub Desktop.
Get Deeply Nested Value in JavaScript
/**
* @param {Object} object
* @param {string|Array<string>} path
* @param {*} [defaultValue]
* @return {*}
*/
export default function get(object, path, defaultValue) {
const path = Array.isArray(pathParam) ? pathParam : pathParam.split('.');
let index = 0;
let length = path.length;
let object = objectParam;
while (object != null && index < length) {
object = object[String(path[index])];
index++;
}
const value = index && index === length ? object : undefined;
return value !== undefined ? value : defaultValue;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment