Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rename keys with ramda js

const orignalArr = [
  {
    personName: 'Joe'
  }
]

expected output:

const convertedArr = [
  {
    name: 'Joe'
  }
]

I'm thinking the renamed keys are defined in an object (but fine if there's a better way to map them):

const keymaps = {
  personName: 'name'
};

How can I do this with Ramda?

Something with R.map

like image 556
Joe Avatar asked Dec 06 '22 09:12

Joe


1 Answers

There is an entry in Ramda's Cookbook for this:

const renameKeys = R.curry((keysMap, obj) =>
  R.reduce((acc, key) => R.assoc(keysMap[key] || key, obj[key], acc), {}, R.keys(obj))
);

const originalArr = [{personName: 'Joe'}]

console .log (
  R.map (renameKeys ({personName: 'name'}), originalArr)
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.js"></script>

But with the ubiquity of ES6, it's pretty easy to write this directly:

const renameKeys = (keysMap) => (obj) => Object.entries(obj).reduce(
  (a, [k, v]) => k in keysMap ? {...a, [keysMap[k]]: v} : {...a, [k]: v},
  {}
)
like image 91
Scott Sauyet Avatar answered Dec 07 '22 22:12

Scott Sauyet