Skip to content

Instantly share code, notes, and snippets.

@gladchinda
Last active November 2, 2020 21:46
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gladchinda/621c624e68345ebe7d2993c4dab7cfc9 to your computer and use it in GitHub Desktop.
Save gladchinda/621c624e68345ebe7d2993c4dab7cfc9 to your computer and use it in GitHub Desktop.
function getValueFromPath(object, path) {
const OBJECT_TYPE = '[object Object]';
const $type = Function.prototype.call.bind(Object.prototype.toString);
// Ensure that path is a string, default to an empty string if not provided.
// Replace bracket notation occurrences on path with dot notation.
// Split path (to array) using the `.` delimeter, discard empty elements.
path = (path ? String(path) : String())
.replace(/\[((?:['"])?)([^[\]]*)\1\]/g, function __replacer__($, $$, key) {
return `.${Number(key) || String(key)}`;
})
.split(/\.+/)
.filter(Boolean);
// Value is originally the root object.
let value = object;
// For every key in the path array, try to access the value at that address.
// Update `value` with the value at that address.
// Break the loop if `value` is `undefined`.
for (const key of path) {
// If value is an object instance or plain JS object and has the given key,
// access the given key on the object. Otherwise, if it is an array, try to
// access the numeric key(index) on the array. Otherwise, it is `undefined`.
try {
value = (value instanceof Object || $type(value) === OBJECT_TYPE) && key in value
? value[key]
: value[value instanceof Array ? Number(key) : key];
if (value === undefined) break;
} catch (e) {
value = undefined;
break;
}
}
return value;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment