Reputation: 2583
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.
Upvotes: 17
Views: 19403
Reputation: 50807
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.
Update, 2023-05-05: the order of arguments to propEq
has recently changed. We would need to swap the parameters in the above, as seen in the REPL.
Upvotes: 29
Reputation: 1
I would use Ramda's find, findIndex and update combined. Let's say your array's name is array and you would like to change the key from the second object of your array. And you would like to to change from '22' to '40'.
const objToChange = R.find(R.propEq('key', 22 ))(array); // To find the object you like to change.
objToChange.key = 40; // Change your desired field.
R.update(R.findIndex(R.propEq('key', 22))(array), objToChange,
patients); // And update the array with the new changed object.
Or just using findIndex ...
const index = R.findIndex(R.propEq('key', 22))(patients);
array[index].key = 40;
Upvotes: 0
Reputation: 673
I had to make some assumptions about the value fo checked and name.
let checked = 'true'
let name = '22'
let input = [{name:'name', key:'21',good: 'true'},
{name: 'another name', key:'22',good:'false'}]
const update = R.map(R.ifElse(R.propEq('key', name), R.assoc('good', checked), (item) => item))
console.log(update(input))
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.24.1/ramda.min.js"></script>
Upvotes: 4