Skip to content

Instantly share code, notes, and snippets.

@rlueder
Forked from microbial/rename.js
Last active May 17, 2024 01:56
Show Gist options
  • Save rlueder/a50b3837690060a5b175882099377e83 to your computer and use it in GitHub Desktop.
Save rlueder/a50b3837690060a5b175882099377e83 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 = (obj, key, newKey) => {
if(_.includes(_.keys(obj), key)) {
obj[newKey] = _.clone(obj[key], true)
delete obj[key]
}
return obj
}
@rlueder
Copy link
Author

rlueder commented Aug 8, 2017

  • replaced _.contains with _.includes so it'll work with lodash 4.x
  • updated to use arrow function and removed semi-colons

works great! 👍

@marshallswain
Copy link

Thanks! I modified it to handle dot syntax for deeply nested props:

import { get, set, unset, has } from 'lodash'

export default (obj, oldKey, newKey) => {
  if (has(obj, oldKey)) {
    set(obj, newKey, get(obj, oldKey))
    unset(obj, oldKey)
  }
  return obj
}

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