Created
July 5, 2018 17:55
-
-
Save lukasbach/cf0cf83054f21e0a6224345181b918ff to your computer and use it in GitHub Desktop.
Replace object members by member name in a deeply nested 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
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