@n3okill/utils
Version:
Many javascript helpers
44 lines • 2.26 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.setProperty = setProperty;
const isArray_1 = require("../type/isArray");
const isString_1 = require("../type/isString");
const isUndefined_1 = require("../type/isUndefined");
const _internal_1 = require("./_internal");
/**
* Set a property in an object
* @param obj The object where to set the property
* @param {string | Array<string>} name The name of the property can be on the form "a.b.c[1].d"
* @param value The value to be defined for the property
* @param {boolean} replace If true will replace the property if it already exists
* @returns The original object (just for chaining purposes)
*/
function setProperty(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
obj, name, value, replace = false) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
let o = obj;
const parts = (0, _internal_1.getNameParts)((0, isString_1.isString)(name) ? name.split(".") : name);
const length = parts.length;
if (parts.length > 1) {
parts.reduce((prev, curr) => {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access, security/detect-object-injection
o[prev] =
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, security/detect-object-injection
!(0, isUndefined_1.isUndefined)(o[prev]) ? o[prev] : parseInt(curr).toString() === curr ? [] : {};
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access, security/detect-object-injection
o = o[prev];
return curr;
});
}
if (o &&
((replace === true && Object.prototype.hasOwnProperty.call(o, parts[length - 1])) ||
!Object.prototype.hasOwnProperty.call(o, parts[length - 1]) ||
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
(0, isArray_1.isArray)(o[parts[length - 1]]))) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
o[parts[length - 1]] = value;
}
return obj;
}
//# sourceMappingURL=setProperty.js.map
;