简体   繁体   中英

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 );
R.map(R.over(R.lensProp('name'), R.replace('John', 'Ben')))(my_data)

R.overR.lensProp

There's no reason to prefer point-free functions. Readability is what really matters:

 var myData = [ new Person("John", 22) , new Person("Johnny", 15) , new Person("Dave", 27) ]; var fixedData = myData.map(fixName); alert(JSON.stringify(fixedData, null, 4)); function fixName(person) { return Object.assign(new Person, person, { name: person.name.replace(/John/g, "Ben") }); } function Person(name, age) { this.name = name; this.age = age; } 

Point-free functions are useful in very limited cases like eta conversion and function composition . Point-free functions should not be treated as the cornerstone of functional programming.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM