diff --git a/src/utils/unset.ts b/src/utils/unset.ts index 2f777db3ba3..766309b1d02 100644 --- a/src/utils/unset.ts +++ b/src/utils/unset.ts @@ -24,41 +24,28 @@ function isEmptyArray(obj: unknown[]) { return true; } -export default function unset(object: any, path: string) { - const updatePath = isKey(path) ? [path] : stringToPath(path); - const childObject = - updatePath.length == 1 ? object : baseGet(object, updatePath); - const key = updatePath[updatePath.length - 1]; - let previousObjRef; +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]; } - for (let k = 0; k < updatePath.slice(0, -1).length; k++) { - let index = -1; - let objectRef; - const currentPaths = updatePath.slice(0, -(k + 1)); - const currentPathsLength = currentPaths.length - 1; - - if (k > 0) { - previousObjRef = object; - } - - while (++index < currentPaths.length) { - const item = currentPaths[index]; - objectRef = objectRef ? objectRef[item] : object[item]; - - if ( - currentPathsLength === index && - ((isObject(objectRef) && isEmptyObject(objectRef)) || - (Array.isArray(objectRef) && isEmptyArray(objectRef))) - ) { - previousObjRef ? delete previousObjRef[item] : delete object[item]; - } - - previousObjRef = objectRef; - } + if ( + index !== 0 && + ((isObject(childObject) && isEmptyObject(childObject)) || + (Array.isArray(childObject) && isEmptyArray(childObject))) + ) { + unset(object, paths.slice(0, -1)); } return object;