deep-get-set
Version:
Set and get values on objects via dot-notation strings.
38 lines (34 loc) • 1 kB
JavaScript
export default function () {
if (arguments.length === 2) return get.apply(null, arguments);
return set.apply(null, arguments);
}
export function get (obj, path) {
var keys = Array.isArray(path) ? path : path.split('.');
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
if (!obj || !Object.hasOwn(obj, key) || isUnsafeKey(key)) {
obj = undefined;
break;
}
obj = obj[key];
}
return obj;
}
export function set (obj, path, value, strict = false) {
var keys = Array.isArray(path) ? path : path.split('.');
for (var i = 0; i < keys.length - 1; i++) {
var key = keys[i];
if (isUnsafeKey(key)) return;
if (!Object.hasOwn(obj, key) && !strict) obj[key] = {};
obj = obj[key];
}
obj[keys[i]] = value;
return value;
}
// Object.hasOwn should be enough, but still...
function isUnsafeKey (key) {
return (Array.isArray(key) && key[0] === '__proto__')
|| key === '__proto__'
|| key === 'constructor'
|| key === 'prototype';
}