Skip to content

Instantly share code, notes, and snippets.

@buren
Created September 5, 2022 16:19
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 buren/1d08ac1a3cf7f8d16ca91e20723c7f76 to your computer and use it in GitHub Desktop.
Save buren/1d08ac1a3cf7f8d16ca91e20723c7f76 to your computer and use it in GitHub Desktop.
Recursively redact keys from object.
recursiveRedact({ a: 1, b: { a: 1, b: 2 } }, new Set(['a']))
// Result
// {
// "a": "[redacted]",
// "b": {
// "a": "[redacted]",
// "b": 2
// }
// }
// 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