Last active
November 27, 2024 19:42
-
-
Save ChecksumFailed/fcd6d2ac60e6b09b053e1dd5c7db5a5f to your computer and use it in GitHub Desktop.
Dot walk object until last property reached
This file contains hidden or 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
| /** | |
| * Walks through an object using dot notation or an array of properties. This could be replaced by option chaining in ECMA2021 | |
| * @param {object} obj - The object to walk through. | |
| * @param {string | string[]} props - The dot notation string or array of properties to traverse. | |
| * @returns {*} - The value of the property at the end of the traversal, or undefined if not found. | |
| * @throws {Error} - Throws an error if the arguments are invalid. | |
| * @private | |
| */ | |
| function _dotWalkObject(obj, props) { | |
| var propsIsArray = Array.isArray(props); | |
| if (typeof obj !== "object" || (!propsIsArray && typeof props !== 'string' )) { | |
| throw new Error("_dotWalkObject: Invalid arguments."); | |
| } | |
| props = propsIsArray ? props : props.replace(/\[(\d+)\]/g,".$1").split('.').filter(Boolean); | |
| return props.reduce(function(acc, key) { | |
| return acc && acc.hasOwnProperty(key) ? acc[key] : undefined; | |
| }, obj); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment