Last active
March 2, 2023 15:14
-
-
Save ChecksumFailed/fcd6d2ac60e6b09b053e1dd5c7db5a5f to your computer and use it in GitHub Desktop.
Dot walk object until last property reached
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
/** | |
* Dot walk object until last property reached | |
* @param {Object} obj obj | |
* @param {Array} props array of object properties | |
* @returns the last object value | |
*/ | |
function recurseObjChildren(obj, props) { | |
props = Array.isArray(props) ? props : props.split('.'); | |
var item = props.shift(); | |
var arrLen = props.length; | |
var isArr = item.match(/(.+)\[(\d+)\]/); | |
var obj = isArr && !obj.hasOwnProperty(item) ? obj[isArr[1]][isArr[2]] : obj[item]; | |
return arrLen == 0 ? obj : recurseObjChildren(obj, props); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment