Ramda Js: Setting property on an object using a value from the same object
11,896
Solution 1
Lenses are not a good fit when the value of one property depends on the value of another property. A lambda is probably best here:
const foo = o => R.assoc('bar', 'foo' + o.foo, o);
foo({foo: 'bar'});
// => {foo: 'bar', bar: 'foobar'}
Solution 2
I had just coded something like the answer from @davidchambers and then made a points-free version, only to show how much simpler the lambda actually is. Rather than throw it out, here's how bad it looks in comparison:
var foo = (obj) => R.assoc('bar', 'foo' + obj.foo, obj);
var foo = R.converge(R.assoc('bar'), [R.pipe(R.prop('foo'), R.concat('foo')), R.identity]);
These two, with an intermediate version are available on the Ramda REPL
Author by
James Flight
Updated on July 06, 2022Comments
-
James Flight over 1 year
Using Ramda Js, I need to create a function that can set one object property using the value of a different property on the same object. My attempt so far is as follows:
var foo = R.set(R.lensProp('bar'), 'foo' + R.prop('foo')); var result = foo({foo:"bar"});
Desired result:
{foo:"bar", bar:"foobar"}
Actual result:
{foo:"bar", bar: "foofunction f1(a) {... etc"}
Clearly I'm misunderstanding something here, and any insights into how to approach this would be appreciated.
-
James Flight almost 8 yearsCheers Scott! Interesting how long winded the points-free version needs to be.
-
Scott Sauyet almost 8 yearsI'm not guaranteeing that there isn't a more concise points-free version. But the lambda expression is already fairly clean.