Skip to content

Instantly share code, notes, and snippets.

@LeoAref
Created May 19, 2017 05:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LeoAref/9e34436c8b140d690733631befc248ba to your computer and use it in GitHub Desktop.
Save LeoAref/9e34436c8b140d690733631befc248ba to your computer and use it in GitHub Desktop.
Immutable object key renaming using Lodash
export function renameKeyName(obj, oldName, newName) {
const clone = cloneDeep(obj);
const keyVal = clone[oldName];
delete clone[oldName];
clone[newName] = keyVal;
return clone;
}
@sbusch
Copy link

sbusch commented Mar 4, 2020

A shallow clone is sufficient for renaming of keys at top level. That can be achieved with Spread operator, if available:

export function renameKeyName(obj, oldName, newName) {
  const { [newName]: value, ...remainingObj } = obj;
  return {
    ...remainingObj,
    [newName]: value,
  };
};

@miaachan
Copy link

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