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 const getDisplayName = 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 to func1 || func2 || func3, which will always return func1. – Scott Sauyet Commented Jul 13, 2018 at 19:16
Add a ment  | 

1 Answer 1

Reset to default 7

You 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