Last active
August 11, 2021 12:42
-
-
Save Tsugami/952d821b303de9b3722ade28e795a432 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
/* | |
dado o seguinte cenário, um objeto que pode ter valores aninhados até 2 níveis, | |
deve-se remover a chave do primeiro nível se alguma das chaves aninhadas | |
for (undefined ou {} ou '' ou null) - 0 não conta | |
*/ | |
const isObject = (v) => typeof v === 'object' && !Array.isArray(v) | |
const isEmptyObject = (obj) => isObject(obj) && (Object.keys(obj).length === 0) | |
const isNull = (v) => v === '' || v === null || v === undefined; | |
const recursiveRemoveNullField = (input, forceNullField) => { | |
const HAS_INVALID_FIELD = 0; | |
const result = Object.entries(input).reduce((acc, [key, value]) => { | |
if (forceNullField && acc === HAS_INVALID_FIELD) return acc; | |
if (isObject(value)) { | |
const obj = recursiveRemoveNullField(value, true); | |
if (isEmptyObject(obj)) { | |
return forceNullField ? HAS_INVALID_FIELD : acc; | |
} else { | |
return { ...acc, [key]: value } | |
} | |
} else if (!isNull(value)) { | |
return { ...acc, [key]: value } | |
} else if (forceNullField) { | |
return HAS_INVALID_FIELD; | |
} | |
return acc; | |
}, {}) | |
return result === HAS_INVALID_FIELD ? {} : result; | |
} | |
const obj = { | |
banana: {hello: "world", check: undefined}, | |
hei: {nested: {deep: undefined, banana: "hello"}}, | |
some1: {back: "tested"}, | |
some2: {back: undefined, test: {}}, | |
some3: 'hellow', | |
some4: undefined | |
} | |
// output sperado | |
// const obj = { | |
// some1: {back: "tested"}, | |
// some3: 'hellow', | |
// } | |
console.log(recursiveRemoveNullField(obj)) |
juliomerisio
commented
Aug 11, 2021
const newObj = <T extends Record<string, any>(obj: T): Partial<T> => Object.entries(obj).reduce((acc, [key, value]) => {
const strValue = JSON.stringify(value, (key, value) =>
value === undefined ? null : value,
);
if (/null|{}/.test(strValue)) {
return acc;
}
return { ...acc, [key]: value };
}, {});
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment