简体   繁体   English

Lodash.get 在 Ramda 中等效

[英]Lodash.get equivalent in Ramda

Is there any built-in Ramda function to retrieve the value giving the path as a string?是否有任何内置的 Ramda 函数来检索以字符串形式给出路径的值? Like:喜欢:

R.path('a.b', {a: {b: 2}}); // I want to get 2

I know that this is possible with path by using an array, like:我知道这可以通过使用数组的path来实现,例如:

R.path(['a', 'b'], {a: {b: 2}});

I can split the path by .我可以通过. and then use it, but before doing it I'd like to know if there is a function already available that works like lodash.get .然后使用它,但在使用它之前,我想知道是否有一个像lodash.get一样可用的函数。

Ramda doesn't handle string paths like lodash do. Ramda 不像 lodash 那样处理字符串路径。 However, you can generate a very close function by using R.pipe , and R.split .但是,您可以使用R.pipeR.split生成非常接近的函数。 Split used to convert an array with dots ( . ) and brackets to an array that R.path can handle. Split 用于将带有点 ( . ) 和括号的数组转换为R.path可以处理的数组。

Notes: this is a very naive implementation, and it will fail for a variety of edge cases because of what is a valid object key in JS.注意:这是一个非常幼稚的实现,由于 JS 中的对象键有效的,因此它会在各种边缘情况下失败。 For example, an edge case like this ['a.b'] - get the property ab from an object that looks like this { 'a.b': 5 } .例如,像这样的边缘情况['a.b'] - 从看起来像这样的对象中获取属性ab { 'a.b': 5 } To handle edge cases you'll have to implement something similar to lodash's internal's stringToPath() function.为了处理边缘情况,你必须实现类似于 lodash 内部的stringToPath()函数的东西。

 const { pipe, path, split } = R; const pathString = pipe(split(/[[\\].]/), path); const result = pathString('a.b')({a: {b: 2}}); console.log(result);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.js"></script>

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

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