Created
September 5, 2022 16:19
-
-
Save buren/1d08ac1a3cf7f8d16ca91e20723c7f76 to your computer and use it in GitHub Desktop.
Recursively redact keys from object.
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
recursiveRedact({ a: 1, b: { a: 1, b: 2 } }, new Set(['a'])) | |
// Result | |
// { | |
// "a": "[redacted]", | |
// "b": { | |
// "a": "[redacted]", | |
// "b": 2 | |
// } | |
// } |
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
// Adapted from https://stackoverflow.com/a/72493889 | |
const recursiveRedact = <T extends Object>(obj: T, keys: Set<string>, visitedIn?: Set<any>): T => { | |
if (typeof obj !== 'object') return obj; | |
const visited = visitedIn ?? new Set(); | |
visited.add(obj); | |
Object.entries(obj).forEach(([key, val]) => { | |
if (keys.has(key)) { | |
obj[key as keyof T] = '[redacted]' as any; | |
} else if (typeof val === 'object' && !visited.has(val)) { | |
recursiveRedact(val, keys, visited); | |
} | |
}); | |
return obj; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment