I am new to Ramda and faced a wall trying to do some Object transformations.
I have one Array of Object, have to map it and transform each Object.
Wanted transformations:
- Rename each object keys
- Add new key to each Object, based on another key (value depends on condition)
Here it is in code:
Initial array:
const items = [
{
id: 1,
name: 'Name 1',
factors: [
{ id: 11, name: '11', },
{ id: 12, name: '12', },
{ id: 13, name: '13', },
{ id: 14, name: '14', },
{ id: 15, name: '15', },
]
},
{
id: 2,
name: 'Name 2',
factors: [],
},
];
Wanted output array:
const items = [
{
key: 1, // changed property key - already done
title: 'Name 1', // changed property key - already done
factors: [
{ id: 11, name: '11', },
{ id: 12, name: '12', },
{ id: 13, name: '13', },
{ id: 14, name: '14', },
{ id: 15, name: '15', },
],
// add property icon (done)
// set icon prop based on factors length
icon: '',
},
{
key: 2,
title: 'Name 2',
// add property icon (done)
// set icon prop based on factors length
icon: 'icon'
},
];
First goal in the above list is completed - I can change property keys of each Object. I also can add a new key to each Object. But I can not set this new property a value based on factors Array.length.
Here is the current code:
const items = [
{
id: 1,
name: 'Name 1',
factors: [
{ id: 11, name: '11', },
{ id: 12, name: '12', },
{ id: 13, name: '13', },
{ id: 14, name: '14', },
{ id: 15, name: '15', },
]
},
{
id: 2,
name: 'Name 2',
},
];
const renameKeys = curry((keysMap, obj) =>
reduce((acc, key) => assoc(keysMap[key] || key, obj[key], acc), {}, keys(obj))
);
const result = map(pipe(
renameKeys({ id: 'key', name: 'title' }),
assoc('icon', '---'), // <= here, set it based on condition - factors.length
), items);
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.27.1/ramda.min.js" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script> const {curry, assoc, map, pipe, reduce, keys} = R </script>