change an object property in array with ramda

amir picture amir · Oct 8, 2017 · Viewed 13k times · Source

I have an array of the object like below :

[{name:'name', key:'21',good: 'true'},
{name: 'another name', key:'22',good:'false'},
...]

now I want to make a change in one of the objects in this array. My first try was this:

const s = R.compose(
  R.assoc('good', checked),
  R.propEq('key', name),
  R.map(),
);

but this code results in that object which I want and only its 'good' property. I want to get the whole array with that change.

Answer

Scott Sauyet picture Scott Sauyet · Oct 8, 2017

I would do it something like this:

const alter = curry((checked, key, items) => map(
  when(propEq('key', key), assoc('good', checked)),
  items
))

alter('true', '22', items)

This has the advantage of including no free variables (such as checked and name in the original.) The currying can be dropped if you're never going to need partial versions of this.

You can see this in action on the Ramda REPL.