deep-get-set-ts
Version:
Deeply get and set values via dot-notation strings respecting type information.
32 lines (31 loc) • 713 B
JavaScript
function u(...t) {
return t.length === 2 ? c(...t) : l(...t);
}
function c(t, r) {
const f = Array.isArray(r) ? r : r.split(".");
for (const e of f) {
if (t == null || !Object.prototype.hasOwnProperty.call(t, e) || i(e))
return;
const n = t[e];
t = n;
}
return t;
}
function l(t, r, f, e = !1) {
const n = Array.isArray(r) ? r.flat(1 / 0) : r.split(".");
for (const s of n.slice(0, -1)) {
if (i(s)) return;
!Object.hasOwn(t, s) && !e && (t[s] = {}), t = t[s];
}
const o = n[n.length - 1];
if (!i(o))
return t[o] = f, f;
}
function i(t) {
return t === "__proto__" || t === "constructor" || t === "prototype";
}
export {
u as default,
c as get,
l as set
};