JavaScript
x
6
1
const orignalArr = [
2
{
3
personName: 'Joe'
4
}
5
]
6
expected output:
JavaScript
1
6
1
const convertedArr = [
2
{
3
name: 'Joe'
4
}
5
]
6
I’m thinking the renamed keys are defined in an object (but fine if there’s a better way to map them):
JavaScript
1
4
1
const keymaps = {
2
personName: 'name'
3
};
4
How can I do this with Ramda?
Something with R.map
Advertisement
Answer
There is an entry in Ramda’s Cookbook for this:
JavaScript
1
9
1
const renameKeys = R.curry((keysMap, obj) =>
2
R.reduce((acc, key) => R.assoc(keysMap[key] || key, obj[key], acc), {}, R.keys(obj))
3
);
4
5
const originalArr = [{personName: 'Joe'}]
6
7
console .log (
8
R.map (renameKeys ({personName: 'name'}), originalArr)
9
)
JavaScript
1
1
1
<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:
JavaScript
1
5
1
const renameKeys = (keysMap) => (obj) => Object.entries(obj).reduce(
2
(a, [k, v]) => k in keysMap ? {a, [keysMap[k]]: v} : {a, [k]: v},
3
{}
4
)
5