Created
August 3, 2023 00:04
-
-
Save koalicioous/004d1116fe7b789b4619683aef1e6aca to your computer and use it in GitHub Desktop.
Get Deeply Nested Value in JavaScript
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
/** | |
* @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