Is it possible to transform an object by modifying and filtering it to create a different shape that is easier to work with after making an API request? I've been struggling to find elegant solutions that don't involve using path
and prop
for every key.
It seems like there should be a more efficient way to reshape objects without explicitly specifying each property. Can anyone suggest a more concise approach?
I've experimented with functions like evolve
and lens
, but I haven't been able to achieve the desired outcome of adding new properties easily.
Edit: I managed to create a mapping function that gets the job done, but I'm curious if there's a better method out there.
Here's what I tried:
const { prop, path, toUpper, map, compose } = R
const baseObject = {
id: 1,
name: 'object-one',
info: {
items: [
{ name: 'item-one', url: '/images/item-one.jpg' },
]
},
}
const createObjectFromSpec = spec => baseObj => R.map(f => f(baseObj), spec);
const createObjectTypeOne = createObjectFromSpec({
id: prop('id'),
name: prop('name'),
image: path(['info', 'items', 0, 'url']),
})
const createObjectTypeTwo = createObjectFromSpec({
id: prop('id'),
name: prop('name'),
itemName: path(['info', 'items', 0, 'name']),
})
console.log(
createObjectTypeOne(baseObject)
)
console.log(
createObjectTypeTwo(baseObject)
)