Created
January 19, 2022 03:35
-
-
Save luiznasciment0/5f535119cea0571023859d27075294b8 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
function getKeysToBeRemoved(key) { | |
const hasDot = key.includes('.'); | |
if (!hasDot) { | |
return [key]; | |
} | |
const [key1, key2] = key.split('.'); | |
return [key1, key2]; | |
} | |
function removePropsFromObject(_obj, keysToRemove) { | |
const obj = JSON.parse(JSON.stringify(_obj)); | |
for (const key of keysToRemove) { | |
const keysToBeRemoved = getKeysToBeRemoved(String(key)); | |
if (keysToBeRemoved.length > 1) { | |
delete obj[keysToBeRemoved[0]][keysToBeRemoved[1]]; | |
continue; | |
} | |
delete obj[keysToBeRemoved[0]]; | |
} | |
return obj; | |
} | |
const test = { a: 1, b: 2, c: { d: 3 } }; | |
console.log(removePropsFromObject(test, ['c.d'])); // { a: 1, b: 2, c: {} } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment