简体   繁体   English

对象中的 ramda JavaScript 数组属性

[英]ramda JavaScript array property in an object

var data = {
   "factors" : [1,2,34]
}

I would like to multiply all the elements in the factors array by 2 using ramda JavaScript and return the updated data object.我想使用 ramda JavaScript 将因子数组中的所有元素乘以 2 并返回更新后的数据对象。

It looks like your attempts are moving in the right direction.看起来您的尝试正朝着正确的方向发展。 It would help if you edited your question to show what you've tried, rather than only including it in the comments.如果您编辑问题以显示您尝试过的内容,而不是仅将其包含在评论中,那将会有所帮助。

There are of course many ways you can do this.当然有很多方法可以做到这一点。

The simplest one might be this, which hard-codes your 2 and factors :最简单的可能是这个,它对你的2factors硬编码:

 const {over, lensProp, map, multiply} = R const multFactors = over(lensProp('factors'), map(multiply(2))) console.log(multFactors({"factors" : [1,2,34]}))
 <script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.js"></script>

But if you want those passed in, then something like this might be better:但是,如果您想要传入的那些,那么这样的事情可能会更好:

 const {over, lensProp, map, multiply} = R const multAllBy = (propName, multiplier, data) => over(lensProp(propName), map(multiply(multiplier)), data) console.log(multAllBy('factors', 2, {"factors" : [1,2,34]}))
 <script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.js"></script>

Note the position of data : it is the last parameter to the function, and it's used only in the last position of the call.注意data的位置:它是函数的最后一个参数,并且只在调用的最后一个位置使用。 In that case, we can create a closer-to-curried version simply by removing the parameter.在这种情况下,我们可以通过删除参数来创建一个更接近柯里化的版本。 But note the way that we have to call it now.但请注意我们现在必须调用它的方式。 That's fine if you're reusing the intermediate function.如果您要重用中间函数,那很好。 If not, this approach gains you nothing.如果没有,这种方法对您没有任何好处。

 const {over, lensProp, map, multiply} = R const multEachBy = (propName, multiplier) => over( lensProp(propName), map(multiply(multiplier)) ) console.log(multEachBy('factors', 2)({"factors" : [1,2,34]}))
 <script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.js"></script>

None of those are point-free.这些都不是毫无意义的。 If you're trying to get a point-free solution or one that what is fully curried the Ramda way (which you could also get by wrapping curry around one of the last two), then this might be more to your liking:如果您想获得一个无积分的解决方案,或者一个完全以 Ramda 方式咖喱的解决方案(您也可以通过将curry包裹在最后两个之一中来获得),那么这可能更符合您的喜好:

 const {over, lensProp, map, multiply, useWith, compose, identity} = R const multEverythingBy = useWith(over, [lensProp, compose(map, multiply), identity]) console.log(multEverythingBy('factors', 2, {"factors" : [1,2,34]}))
 <script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.js"></script>

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

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