Emi
Emi

Reputation: 5085

Lodash.get equivalent in Ramda

Is there any built-in Ramda function to retrieve the value giving the path as a string? 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:

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.

Upvotes: 5

Views: 3879

Answers (1)

Ori Drori
Ori Drori

Reputation: 193037

Ramda doesn't handle string paths like lodash do. However, you can generate a very close function by using R.pipe, and R.split. Split used to convert an array with dots (.) and brackets to an array that R.path can handle.

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. For example, an edge case like this ['a.b'] - get the property a.b from an object that looks like this { 'a.b': 5 }. To handle edge cases you'll have to implement something similar to lodash's internal's stringToPath() function.

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>

Upvotes: 4

Related Questions