admin管理员组文章数量:1356291
How i write the code as functional if i has the value like this
const data = {
name: null,
email: null,
username: 'johndoo'
}
in this case if i write the function that return the display name i just wrote data.name || data.email || data.username
I try to use ramda like
const getName = R.prop('name')
const getEmail = R.prop('email')
const getUsername = R.prop('username')
const getDisplayName = getName || getEmail || getUsername
but doesn't work, how to write it in ramdajs
How i write the code as functional if i has the value like this
const data = {
name: null,
email: null,
username: 'johndoo'
}
in this case if i write the function that return the display name i just wrote data.name || data.email || data.username
I try to use ramda like
const getName = R.prop('name')
const getEmail = R.prop('email')
const getUsername = R.prop('username')
const getDisplayName = getName || getEmail || getUsername
but doesn't work, how to write it in ramdajs
Share Improve this question asked Jul 11, 2018 at 18:05 stahyzstahyz 1011 gold badge2 silver badges6 bronze badges 3- My first question is why you want to rewrite this with Ramda? While it could be done, I'm sure, what advantage do you expect to gain? – Scott Sauyet Commented Jul 11, 2018 at 19:37
-
As @ScottSauyet said, what are you trying to acplish? You shouldn't force to use Ramda nor any other library if not required. If you just want to get the
displayUsername
in the specified order, that should be fine. Being that said, unless you need the other three variables, I would just do constgetDisplayName = R.prop('name') || R.prop('email') || R.prop('username')
– rdarioduarte Commented Jul 13, 2018 at 18:04 -
@R.DarioDuarte: That won't work, as the OP already noted.
R.prop('name')
and the others are functions, so this is equivalent tofunc1 || func2 || func3
, which will always returnfunc1
. – Scott Sauyet Commented Jul 13, 2018 at 19:16
1 Answer
Reset to default 7You need to use a logical or R.either
:
const getDisplayName = R.either(getName, R.either(getEmail, getUsername))
Or more pact with R.reduce
:
const getDisplayName = R.reduce(R.either, R.isNil)([getName, getEmail, getUsername])
const data = {
name: null,
email: null,
username: 'johndoo'
}
const getName = R.prop('name')
const getEmail = R.prop('email')
const getUsername = R.prop('username')
const eitherList = R.reduce(R.either, R.isNil)
const getDisplayName = eitherList([getName, getEmail, getUsername])
console.log(getDisplayName(data))
<script src="//cdnjs.cloudflare./ajax/libs/ramda/0.25.0/ramda.min.js"></script>
本文标签: javascriptget value if not null with ramda jsStack Overflow
版权声明:本文标题:javascript - get value if not null with ramda js - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743977726a2570943.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论