Skip to content

Instantly share code, notes, and snippets.

@microbial
Last active May 17, 2024 01:54
Show Gist options
  • Save microbial/b99af0a7eb11cb680c14 to your computer and use it in GitHub Desktop.
Save microbial/b99af0a7eb11cb680c14 to your computer and use it in GitHub Desktop.
lodash helpers - rename (renames object keys)
/*
* var person = { firstName: 'bill', lastName: 'johnson' }
*
* person = _.rename(person, 'firstName', 'first')
* person = _.rename(person, 'lastName', 'last')
*
* console.log(person) // { first: 'bill', last: 'johnson' }
*/
_.rename = function(obj, key, newKey) {
if(_.includes(_.keys(obj), key)) {
obj[newKey] = _.clone(obj[key], true);
delete obj[key];
}
return obj;
};
@christophemarois
Copy link

Immutable way of renaming a key in modern vanilla JS:

let obj = { oldKey: 1, b: 2, c: 3 }
const { oldKey: newKey, ...rest } = obj
obj = { newKey, ...rest }
obj // => { newKey: 1, b: 2, c: 3 }

@p77u4n
Copy link

p77u4n commented Feb 26, 2021

I think this function should preserve the input parameter

export const rename = (obj, key, newKey) => {
  const newObj = { ...obj };
  if(_.includes(_.keys(newObj), key)) {
    newObj[newKey] = _.clone(newObj[key], true);

    delete newObj[key];
  }

  return newObj;
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment