简体   繁体   English

模拟 lodash 库中的 Ramda.pathOr

[英]Analog Ramda.pathOr in lodash library

What is method equal ramda.pathOr in lodash library? lodash 库中的方法等于ramda.pathOr是什么?

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?我如何编写此 lodash 语法?

You could use _.get and hand over object, path and an optional default value.您可以使用_.get并移交对象、路径和可选的默认值。

 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>

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:根据 Nina 的回答使用get的替代方法,lodash/fp 中的getOr function 具有类似于 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 .请参阅https://github.com/lodash/lodash/wiki/FP-Guide ,或在How lodash / fp getOr works中查看答案示例。

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

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