File size: 1,235 Bytes
1e92f2d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
import isEmptyObject from './isEmptyObject';
import isKey from './isKey';
import isObject from './isObject';
import isUndefined from './isUndefined';
import stringToPath from './stringToPath';
function baseGet(object: any, updatePath: (string | number)[]) {
const length = updatePath.slice(0, -1).length;
let index = 0;
while (index < length) {
object = isUndefined(object) ? index++ : object[updatePath[index++]];
}
return object;
}
function isEmptyArray(obj: unknown[]) {
for (const key in obj) {
if (obj.hasOwnProperty(key) && !isUndefined(obj[key])) {
return false;
}
}
return true;
}
export default function unset(object: any, path: string | (string | number)[]) {
const paths = Array.isArray(path)
? path
: isKey(path)
? [path]
: stringToPath(path);
const childObject = paths.length === 1 ? object : baseGet(object, paths);
const index = paths.length - 1;
const key = paths[index];
if (childObject) {
delete childObject[key];
}
if (
index !== 0 &&
((isObject(childObject) && isEmptyObject(childObject)) ||
(Array.isArray(childObject) && isEmptyArray(childObject)))
) {
unset(object, paths.slice(0, -1));
}
return object;
}
|