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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With