Skip to content

Instantly share code, notes, and snippets.

@circAssimilate
Created July 10, 2020 21:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save circAssimilate/d182272afacbc8ec16b9c2fbc649c37a to your computer and use it in GitHub Desktop.
Save circAssimilate/d182272afacbc8ec16b9c2fbc649c37a to your computer and use it in GitHub Desktop.
Two options for Formik method additions based off of existing Formik code
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