4

What is the easiest way to transform the following object?

// original
{ 
  name: "bob", 
  age: 24 
} 

// result
{ 
  name: "bob", 
  age: 24, 
  description: "bob is 24 years old" 
}

I can use lens to update a single property, such as incrementing the age. But I'm not sure how to go about deriving from multiple properties into a single one.

user1164937
  • 1,979
  • 2
  • 21
  • 29

1 Answers1

4

You can use R.applySpec to create an object with the derived property. To merge it with the original object use R.chain, and R.merge (I've used R.mergeLeft to make it the last property).

Applying R.chain to functions (chain(f, g)(x)) is the equivalent of f(g(x), x). In this case x is the original object, g is R.applySpec (create the object from x), and f is R.mergeLeft (mergeLeft g(x) and x).

const { chain, mergeLeft, applySpec } = R

const getDescription = ({ name, age }) => `${name} is ${age} years old`

const fn = chain(mergeLeft, applySpec({
  description: getDescription,
}))

const result = fn({
  name: "bob", 
  age: 24 
})

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.27.1/ramda.js"></script>

Without Ramda you can get the same result by using object spread to include the original object's properties:

const getDescription = ({ name, age }) => `${name} is ${age} years old`

const fn = o => ({
  ...o,
  description: getDescription(o),
});

const result = fn({
  name: "bob", 
  age: 24 
})

console.log(result)
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
  • Thanks. Expanding on this a bit, my actual goal is to do something like `pipe(incrementAge, withDescription, ...)` for objects with many more properties. This would allow me to create modular functions instead of transforming everything at once. Is this the recommended approach or is there a better way? – user1164937 Aug 01 '20 at 20:04
  • If I understand correctly - pipe passes all params to the first function, so you can't handle each param separately, and then combine them. If you need to handle them before create the description, you can R.evolve them, and then combine them. If you need to generate multiple derived properties R.applySpec is enough. – Ori Drori Aug 01 '20 at 20:46
  • 1
    This is a nicer Ramda solution than I was imagining. +1. This isn't the first time that I've noticed a need for a function that combines `evolve` and `applySpec`, one that acts like `evolve` but also supplies the entire object to the transformation functions. I'm leaving on vacation in a matter of hours, but perhaps I'll look at adding it to Ramda o my return, – Scott Sauyet Aug 02 '20 at 00:23