Skip to content

Instantly share code, notes, and snippets.

@LeeCheneler
Last active December 8, 2023 13:43
Show Gist options
  • Save LeeCheneler/dff367bff2b9c6182dba19390e106278 to your computer and use it in GitHub Desktop.
Save LeeCheneler/dff367bff2b9c6182dba19390e106278 to your computer and use it in GitHub Desktop.
Sanitize keys in an object
import crypto from "crypto";
export const sanitize = (object: Record<string, unknown>, keysToHash: string[]): Record<string, unknown> => {
if (!object) {
return object;
}
const result: Record<string, unknown> = {};
Object.entries(object).forEach(([key, value]) => {
if (!value) {
result[key] = value;
return;
}
if (keysToHash.includes(key)) {
result[key] = crypto.createHash("sha256").update(JSON.stringify(value)).digest("hex");
return;
}
if (Array.isArray(value)) {
result[key] = value.map((item) => sanitize(item as Record<string, unknown>, keysToHash));
return;
}
if (typeof value === "object" && !(value instanceof Date)) {
result[key] = sanitize(value as Record<string, unknown>, keysToHash);
return;
}
result[key] = value;
});
return result;
};
const payload = {
id: 1,
name: "Lee",
};
const sanitizedPayload = sanitize(payload, ["name"]);
console.log(sanitizedPayload);
// { id: 1, name: "<hash>" }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment