Created
May 19, 2017 05:49
-
-
Save LeoAref/9e34436c8b140d690733631befc248ba to your computer and use it in GitHub Desktop.
Immutable object key renaming using Lodash
This file contains hidden or 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
export function renameKeyName(obj, oldName, newName) { | |
const clone = cloneDeep(obj); | |
const keyVal = clone[oldName]; | |
delete clone[oldName]; | |
clone[newName] = keyVal; | |
return clone; | |
} |
export function renameKeyName(obj, oldName, newName) { const { [newName]: value, ...remainingObj } = obj; return { ...remainingObj, [newName]: value, }; };
Thanks for sharing but found there is a mistake where newName
should be oldName
instead.
export function renameKeyName(obj, oldName, newName) {
const { [oldName]: value, ...remainingObj } = obj;
return {
...remainingObj,
[newName]: value,
};
};
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A shallow clone is sufficient for renaming of keys at top level. That can be achieved with Spread operator, if available: