@marcopeg/dotted
Version:
Extract data from an object using a dotted notation
31 lines (23 loc) • 782 B
JavaScript
;
exports.__esModule = true;
exports.dottedSet = void 0;
var scalars = ['number', 'string', 'boolean'];
var dottedSet = function dottedSet(source, path, value) {
if (scalars.includes(typeof source)) {
return value;
}
if (!source) {
return dottedSet({}, path, value);
}
var tokens = path.split('.');
var setKey = tokens.pop(); // get a reference to the deeper layer represented by the path
var target = tokens.reduce(function (curr, key) {
return curr[key] = curr[key] || {};
}, source); // set the value at the requested key level
target[setKey] = value;
return source;
};
exports.dottedSet = dottedSet;
dottedSet.immutable = function (source, path, value) {
return dottedSet(JSON.parse(JSON.stringify(source)), path, value);
};