简体   繁体   English

Ramda JS:如何执行一个地图,我在每个对象上为R.replace调用给定属性?

[英]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: 我想转换数据,以便在每个名称属性中将子字符串“John”替换为“Ben”,所以它看起来像这样:

[
  {
    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? 我如何使用Ramda函数执行此操作?

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 . 无点函数在非常有限的情况下非常有用,例如eta转换函数组合 Point-free functions should not be treated as the cornerstone of functional programming. 无点函数不应被视为函数式编程的基石。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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