Skip to content

Instantly share code, notes, and snippets.

@gaurangrshah
Last active April 27, 2021 16:17
Show Gist options
  • Save gaurangrshah/39d5afa90e2461bc07162c0716905fd0 to your computer and use it in GitHub Desktop.
Save gaurangrshah/39d5afa90e2461bc07162c0716905fd0 to your computer and use it in GitHub Desktop.
function injectField (obj, { name, value }) {
return {...obj, [name]: value}
}
let obj = {x: 20, y: {z: 30}};
//long version
const makeDeepClone = (obj) => {
let newObject = {};
Object.keys(obj).map(key => {
if(typeof obj[key] === 'object'){
newObject[key] = make DeepClone(obj[key]);
} else {
newObject[key] = obj[key];
}
});
return neObject;
}
const cloneObj = makeDeepClone(obj);
//Shorthand
const cloneObj = JSON.parse(JSON.stringify(obj));
export function isEmpty(value) {
return (
value === undefined ||
value === null ||
(typeof value === "object" && Object.keys(value).length === 0) ||
(typeof value === "string" && value.trim().length === 0)
);
}
export function removeEmptyFromObject(obj) {
const empty = Object.assign(
...Object.keys(obj)
.map((key) => !isEmpty(obj[key]) && { [key]: obj[key] })
.filter(Boolean)
);
return empty;
}
export function removeEmptyFromObjectRecursively(obj) {
let newObj = {};
Object.keys(obj).forEach((key) => {
if (obj[key] === Object(obj[key])) newObj[key] = removeEmpty(obj[key]);
else if (isEmpty(obj[key])) newObj[key] = obj[key];
});
return newObj;
}
export const removeKeys = (obj, keys) => obj !== Object(obj)
? obj
: Array.isArray(obj)
? obj.map((item) => removeKeys(item, keys))
: Object.keys(obj)
.filter((k) => !keys.includes(k))
.reduce(
(acc, x) => Object.assign(acc, { [x]: removeKeys(obj[x], keys) }),
{}
)
export function removeKeysRecurr(obj, keys) {
// @link https://gist.github.com/aurbano/383e691368780e7f5c98#gistcomment-3560352
/**
* @SCOPE: remove keys from a list off of an object or array of objects recursively
*/
return obj !== Object(obj)
? obj
: Array.isArray(obj)
? obj.map((item) => removeKeysRecurr(item, keys))
: remove(([k]) => !keys.includes(k), obj);
}
export function removeRecurr(fn, obj) {
// @SCOPE: runs a function against every key in an object or array of objects
return obj !== Object(obj)
? obj
: Array.isArray(obj)
? obj.map((item) => removeRecurr(fn, item))
: remove(fn, obj);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment