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)