2

What is method equal ramda.pathOr in lodash library?

R.pathOr('N/A', ['a', 'b'], {a: {b: 2}}); //=> 2
R.pathOr('N/A', ['a', 'b'], {c: {b: 2}}); //=> "N/A"

How I can write this lodash syntax?

OliverRadini
  • 6,238
  • 1
  • 21
  • 46

2 Answers2

2

You could use _.get and hand over object, path and an optional default value.

var value = _.get({ a: { b: 2 } }, ['a', 'b'], 'N/A');

console.log(value);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • 1
    `_.get()` already has an optional default value: `var value = _.get({ a: { b: 2 } }, ['a', 'b'], 'N/A')` – Andreas Jan 14 '19 at 14:14
0

An alternative to using lodash's get as per Nina's answer, the getOr function in lodash/fp has argument order and currying similar to Ramda:

const {getOr} = require('lodash/fp');
getOr('N/A', ['a', 'b'], { a: { b: 2 } } );   // 2
getOr('N/A', ['a', 'b'])({ c: { b: 2 } } );   // 'N/A'

See https://github.com/lodash/lodash/wiki/FP-Guide, or for an example the answer at How lodash / fp getOr works .

phhu
  • 1,462
  • 13
  • 33