使用 ramda js 如果不为空则获取值
get value if not null with ramda js
如果我有这样的值,我如何编写功能代码
const data = {
name: null,
email: null,
username: 'johndoo'
}
在这种情况下,如果我编写函数 return 我刚刚写的显示名称 data.name || data.email || data.username
我尝试像这样使用 ramda
const getName = R.prop('name')
const getEmail = R.prop('email')
const getUsername = R.prop('username')
const getDisplayName = getName || getEmail || getUsername
但是不行,ramdajs怎么写
您需要使用逻辑或 R.either
:
const getDisplayName = R.either(getName, R.either(getEmail, getUsername))
或更紧凑 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.com/ajax/libs/ramda/0.25.0/ramda.min.js"></script>
如果我有这样的值,我如何编写功能代码
const data = {
name: null,
email: null,
username: 'johndoo'
}
在这种情况下,如果我编写函数 return 我刚刚写的显示名称 data.name || data.email || data.username
我尝试像这样使用 ramda
const getName = R.prop('name')
const getEmail = R.prop('email')
const getUsername = R.prop('username')
const getDisplayName = getName || getEmail || getUsername
但是不行,ramdajs怎么写
您需要使用逻辑或 R.either
:
const getDisplayName = R.either(getName, R.either(getEmail, getUsername))
或更紧凑 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.com/ajax/libs/ramda/0.25.0/ramda.min.js"></script>