Skip to content

Instantly share code, notes, and snippets.

@ComfortablyCoding
Created March 22, 2022 05:25
Show Gist options
  • Save ComfortablyCoding/c27171dd5281b90ac3383adea732417b to your computer and use it in GitHub Desktop.
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
"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