@pinuts/bsr-uikit-relaunch
Version:
BSR UI-KIT Relaunch
43 lines (41 loc) • 1.46 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.setByPath = exports.getByPath = exports.default = void 0;
/**
* Set a value recursive on an object by defining the path.
* Missing path elements will be created as Object.
*
* @param {Object} object Object the value should be set into.
* @param {String|Array} path Dot-separated path to the target property (or the path elements as array).
* @param {*} value The value to set
* @function Objects.set
*/
const setByPath = (object, path, value) => {
if (!path) return;
const pathAr = Array.isArray(path) ? path : path.split('.');
for (let key = pathAr.shift(); key; key = pathAr.shift()) {
object = object[key] = pathAr.length ? object[key] || {} : value;
}
};
/**
* Read a value from an arbitrary object, following a dot-separated path through the properties.
*
* @param {Object} object the object to read
* @param {String|Array} path Dot-separated path to property containing the wanted value (or path elements as array).
* @return {*} undefined if not found
* @function Objects.get
*/
exports.setByPath = setByPath;
const getByPath = (object, path) => {
if (!path) return;
const pathAr = Array.isArray(path) ? path : path.split('.');
let value = object;
for (let i = 0; i < pathAr.length; i++) {
value = value ? value[pathAr[i]] : undefined;
}
return value;
};
exports.getByPath = getByPath;
var _default = exports.default = {};