Last active
November 2, 2020 21:46
-
-
Save gladchinda/621c624e68345ebe7d2993c4dab7cfc9 to your computer and use it in GitHub Desktop.
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
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