Ryan Jarvis Ryan Jarvis - 6 months ago 21
Javascript Question

Ramda JS: How to perform a map where I call R.replace for a given property on each object?

Given the following data:

const my_data = [
{
name: "John",
age: 22
},
{
name: "Johnny",
age: 15
},
{
name: "Dave",
age: 27
}
]


I want to transform the data such that the substring "John" is replaced with "Ben" in each of the name properties so it looks like this:

[
{
name: "Ben",
age: 22
},
{
name: "Benny",
age: 15
},
{
name: "Dave",
age: 27
}
]


I want to do so in the proper functional way (I think is points-free but I am still learning), so I can reuse this in a pipeline, say first reducing by age and then doing the replace, or doing the replace first then doing a sort. How would I do this using the Ramda functions?

var fix_names = ???
var fixed_data = R.map( fix_names, my_data );

Answer
R.map(R.over(R.lensProp('name'), R.replace('John', 'Ben')))(my_data)

See R.over and R.lensProp.