merge-change
Version:
Advanced library for deep merging, patching, and immutable updates of data structures. Features declarative operations for specific merging behaviors, property management, custom type merging rules, and difference tracking. Supports complex data transform
40 lines • 1.73 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.set = set;
const split_path_1 = require("../split-path");
const has_method_1 = require("../has-method");
/**
* Sets a value at the specified path. If the path is not found in obj, the corresponding property will be created
* @param obj - Object in which the value is set
* @param path - Path in the object where the value is set
* @param value - Value to be set
* @param skipExisting - If true, do not replace existing values (set only if absent)
* @param separator - Separator in a property path
* @returns Previous value at the specified path
*/
function set(obj, path, value, skipExisting = false, separator = '.') {
const parts = (0, split_path_1.splitPath)(path, separator);
if (parts.length === 0)
return obj;
let current = obj;
// Traverse the object using parts until the last part
for (let i = 0; i < parts.length - 1; i++) {
const part = parts[i];
if (current[part] === undefined || current[part] === null) {
// Create an object or array based on the next part
const nextPart = parts[i + 1];
current[part] = typeof nextPart === 'number' ? [] : {};
}
const nextValue = current[part];
current = ((0, has_method_1.hasMethod)(nextValue, 'toJSON') ? nextValue.toJSON() : nextValue);
}
// Update the final property
const lastPart = parts[parts.length - 1];
const currentValue = current[lastPart];
// If it's the last element of the path, set the value
if (!skipExisting || currentValue === void 0) {
current[lastPart] = value;
}
return currentValue;
}
//# sourceMappingURL=index.js.map