Skip to content

Instantly share code, notes, and snippets.

@microbial
Last active February 26, 2021 04:36
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • 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;
};
@clairePoyo
Copy link

Thanks, exactly what i was looking for !

@mmcguff
Copy link

mmcguff commented May 21, 2020

Please advise that .contains needed to be changed for .includes to work for me.

@microbial
Copy link
Author

Thanks!

@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