The ability to reply to discussions is limited to PRO members. Want to join in the discussion? Click here to subscribe now.

Declaratively Map Data Transformations to Object Properties Using Ramda evolve

Declaratively Map Data Transformations to Object Properties Using Ramda evolve

2:44
We don't always control the data we need in our applications, and that means we often find ourselves massaging and transforming our data. In this lesson, we'll learn how to transform objects in a declarative way using ramda's evolve function.
Watch this lesson now
Avatar
egghead.io

We don't always control the data we need in our applications, and that means we often find ourselves massaging and transforming our data. In this lesson, we'll learn how to transform objects in a declarative way using ramda's evolve function.

Avatar
Vamshi

Very helpful!

Avatar
Vijay

I would like to know if we can toggle the state of an object's property if both the object and property are passed as parameters using ramda.

In reply to egghead.io
Avatar
Andrew Van Slaars

Vijay,

Sure, you could handle this a few different ways. One would be to just create a function and use a couple of Ramda's functions to accomplish this:

const toggleProp = (propName, target) => {
  const val = prop(propName, target)
  return assoc(propName, not(val), target)
}

You could also build up the assoc function call and make it point free, but it's not as readable:

const fst = (a, b) => a
const snd = (a, b) => b
const toggleProp = converge(assoc, [fst, compose(not, prop), snd])

Or you could create a function that internally uses lenses:

const toggleProp = (propName, target) => over(lensProp(propName), not, target)

In any of these cases, you would pass in the name of the boolean property you want to toggle and the object. If you wanted to pass these in in two different calls, you could wrap the whole function in curry or curryN with 2 as your first argument.

Hope this helps.

In reply to Vijay
Avatar
Vijay

Andrew,
Thanks. All three are great solutions, but I liked the third one with the combination of curry.

In reply to Andrew Van Slaars
HEY, QUICK QUESTION!
Joel's Head
Why are we asking?