Skip to content

Back to Snippets

deepGet/Set()

function deepGet(obj, key) {
const parts = key.split('.');
let curr = obj, part;
while (curr !== undefined && curr !== null && (part = parts.shift())) {
curr = curr[part];
}
return parts.length ? undefined : curr;
}
function deepSet(obj, key, val) {
const parts = key.split('.');
const last_key = parts.pop();
let curr = obj, part;
while ((part = parts.shift())) {
if (!Object.hasOwn(curr, part)) {
curr[part] = {};
}
curr = curr[part];
}
curr[last_key] = val;
}