@ou-imdt/utils
Version:
Utility library for interactive media development
24 lines (21 loc) • 826 B
JavaScript
import splitPropertyPath from './splitPropertyPath.js';
/**
* Retrieves the value at the specified path of an object.
* Supports propertyPathRegex groups @see {@link propertyPathRegex}.
* @param {object} target - The object from which to retrieve the value.
* @param {string} path - The dot/bracket notation path specifying the value's location.
* @returns {*} The value at the specified path, or an empty string if not found.
*/
export default function getObjectProperty(target, path) {
const parts = splitPropertyPath(path, true);
for (const { key, type, part } of parts) {
path = path.slice(part.length);
target = target?.[key];
if (type === '[]') {
return target?.map((_, index, array) => {
return getObjectProperty(array, `[${index}]${path}`);
});
}
}
return target;
}