Created
March 22, 2022 05:25
-
-
Save ComfortablyCoding/c27171dd5281b90ac3383adea732417b to your computer and use it in GitHub Desktop.
Helper function for obtaining a data attribute without the need to go through additional context
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
"use strict"; | |
/** | |
* Get the value following the `path` for the provided object. | |
* Returns undefined if not found unless a default value is provided | |
* | |
* @param {Object} object The object to check | |
* @param {Array|String} path The path to the object attribute | |
* @param {any} defaultValue The value to return instead of undefined. | |
* @returns {any} The resolved value | |
*/ | |
function getAttribute(object, path, defaultValue) { | |
const attributes = typeof path === "string" ? path.split(".") : path; | |
const depth = attributes.length; | |
let index = 0; | |
while (object != null && index < depth) { | |
// skip the cycle count for data or attributes meta | |
if (object && object.data) { | |
object = object.data; | |
} else if (object && object.attributes) { | |
object = object.attributes; | |
} else { | |
object = object[attributes[index++]]; | |
} | |
} | |
return object || defaultValue; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment