Created
July 10, 2020 21:00
-
-
Save circAssimilate/d182272afacbc8ec16b9c2fbc649c37a to your computer and use it in GitHub Desktop.
Two options for Formik method additions based off of existing Formik code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function deleteField(obj: any, path: string) { | |
let res = clone(obj); // this keeps inheritance when obj is a class | |
let resVal = res; | |
let i = 0; | |
let pathArray = toPath(path); | |
for (; i < pathArray.length - 1; i++) { | |
var currentPath = pathArray[i]; | |
let currentObj = get(obj, pathArray.slice(0, i + 1)); | |
if (currentObj && (isObject(currentObj) || Array.isArray(currentObj))) { | |
resVal = resVal[currentPath] = clone(currentObj); | |
} else { | |
const nextPath = pathArray[i + 1]; | |
resVal = resVal[currentPath] = | |
isInteger(nextPath) && Number(nextPath) >= 0 ? [] : {}; | |
} | |
} | |
delete resVal[pathArray[i]]; | |
// If the path array has a single element, the loop did not run. | |
// Deleting on `resVal` had no effect in this scenario, so we delete on the result instead. | |
if (i === 0) { | |
delete res[pathArray[i]]; | |
} | |
return res; | |
} | |
function replaceField(obj: any, path: string, newKey: string, newValue: any) { | |
let res = clone(obj); // this keeps inheritance when obj is a class | |
let resVal = res; | |
let i = 0; | |
let pathArray = toPath(path); | |
for (; i < pathArray.length - 1; i++) { | |
var currentPath = pathArray[i]; | |
let currentObj = get(obj, pathArray.slice(0, i + 1)); | |
if (currentObj && (isObject(currentObj) || Array.isArray(currentObj))) { | |
resVal = resVal[currentPath] = clone(currentObj); | |
} else { | |
const nextPath = pathArray[i + 1]; | |
resVal = resVal[currentPath] = | |
isInteger(nextPath) && Number(nextPath) >= 0 ? [] : {}; | |
} | |
} | |
delete resVal[pathArray[i]]; | |
resVal[newKey] = newValue; | |
// If the path array has a single element, the loop did not run. | |
// Deleting on `resVal` had no effect in this scenario, so we delete on the result instead. | |
if (i === 0) { | |
delete res[pathArray[i]]; | |
res[newKey] = newValue; | |
} | |
return res; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment