Skip to content

Instantly share code, notes, and snippets.

@jaredpalmer
Last active August 9, 2020 06:58
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jaredpalmer/0f87cb5a05ada1d4e5115bf5dea02f54 to your computer and use it in GitHub Desktop.
Save jaredpalmer/0f87cb5a05ada1d4e5115bf5dea02f54 to your computer and use it in GitHub Desktop.
Replace all values of a given key
/**
* Return a copy of an object, but with values of a key replaced with value of provided key-value object.
* Useful for duplicating highly nested object, but generating new values for a key (e.g. `id`)
*
*
* @param obj An object
* @param keyToReplace The key of the values needed to be swapped
* @param mapOfOldToNewValues A key-value object with a keys of old values mapped to new ones (used for swapping)
*
* @example
* const oldToNewIds = {
* 'abc': '123',
* 'xyz': '456'
* }
*
* const initialObj = {
* 'abc': {
* id: 'abc',
* },
* 'xyz': {
* id: 'xyz'
* parentId: 'abc'
* }
* }
*
* console.log(replaceValues(initialObj, 'id', oldToNewIds))
* ==>
* {
* '123': {
* id: '123',
* },
* '456': {
* id: '456'
* parentId: '123'
* }
* }
*/
function replaceValues<T>(
obj: T,
keyToReplace: string,
mapOfOldToNewValues: Record<string, string>
): T {
// JSON.parse has a second parameter called a reviver that is
// a function transforms the results. This function is called
// for each member of the object. If a member contains nested
// objects, the nested objects are transformed before the
// parent object is. We can exploit that to deeply transform
// any object
return JSON.parse(JSON.stringify(obj), (key, value) => {
if (key === keyToReplace && mapOfOldToNewValues.hasOwnProperty(value)) {
return mapOfOldToNewValues[value];
}
return value;
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment