5

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.

Emi
  • 4,597
  • 2
  • 31
  • 34

1 Answers1

3

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>
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
  • 1
    Using Ramda here probably just adds (lots of?) unnecessary overhead. About 5 years ago, before I knew about lodash's get/set (and possibly before they made it into the library) I wrote what I needed with vanilla Javascript. Not faulting your answer by any means, just an observation. – Dexygen Dec 05 '19 at 16:57
  • I think that if you want to use Ramda, just stick to the array paths. – Ori Drori Dec 05 '19 at 16:57
  • 1
    @GeorgeJempty: Ramda originally had the string version, but there is a failure mode that the team wasn't willing to accept, namely keys with a dot in the name. This is a very easy function to write (perhaps just `(p, o) => p.split('.').reduce((o, k) => (o || {})[k], o)`, which I haven't tested), but determining if it's the right function is a very different call for user code versus a public library. – Scott Sauyet Dec 05 '19 at 17:12
  • 2
    @OriDrori: I don't think there is any reason not to use your version above instead of the one Ramda supplies. But you have to know for sure that your objects do not contain keys with dots. A library can't know that, but you might for your own code-base. – Scott Sauyet Dec 05 '19 at 17:15
  • I also probably wouldn't try to support braces. `a.1.b` should work to get the `b` property of the array element at index `1` in the `a` property of your object. So this can simplify to what I posted in my comment to George. But of course if the goal is to move lodash code to Ramda, things might be different. – Scott Sauyet Dec 05 '19 at 17:26