Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

change an object property in array with ramda

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.

like image 397
amir Avatar asked Oct 08 '17 06:10

amir


People also ask

How do you change an object property in an array?

To update an object's property in an array of objects, use the map() method to iterate over the array. On each iteration, check if the current object is the one to be updated. If it is, modify the object and return the result, otherwise return the object as is. Copied!

Is ramda better than Lodash?

Ramda is generally a better approach for functional programming as it was designed for this and has a community established in this sense. Lodash is generally better otherwise when needing specific functions (esp. debounce ).

What is Ramda in JavaScript?

Ramda is a JavaScript library that makes functional programming simple. While JavaScript libraries with functional capabilities have been around for a while, Ramda acts as a complete standard library specifically catered to the functional paradigm. Ramda is a JavaScript library that makes functional programming simple.

Should I use ramda?

Yep. Ramda is an excellent library for getting started on thinking functionally with JavaScript. Ramda provides a great toolbox with a lot of useful functionality and decent documentation.


1 Answers

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.

like image 171
Scott Sauyet Avatar answered Sep 23 '22 16:09

Scott Sauyet