Skip to content

Instantly share code, notes, and snippets.

@lukasbach
Created July 5, 2018 17:55
Show Gist options
  • Save lukasbach/cf0cf83054f21e0a6224345181b918ff to your computer and use it in GitHub Desktop.
Save lukasbach/cf0cf83054f21e0a6224345181b918ff to your computer and use it in GitHub Desktop.
Replace object members by member name in a deeply nested object
const deepReplace = (obj: object, keyName: string, replacer: (from: any) => string) => {
for (const key in obj) {
if (key === keyName) {
obj[key] = replacer(obj[key]);
} else if (Array.isArray(obj[key])) {
(obj[key] as any[]).forEach(member => deepReplace(member, keyName, replacer));
} else if (typeof obj[key] === "object") {
deepReplace(obj[key], keyName, replacer);
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment