Ramda(或其他FP lib)用于选择null键的用法

时间:2018-01-02 04:22:21

标签: javascript ramda.js

我们说我的数据结构如下:

let slots = {
  7 : [ 'a', 'b', 'c' ],
  8 : [ 'd', 'e', 'f' ]
}
let names = {
  a : { name : 'Joe' },
  b : { name : 'Doe' },
  c : { name : 'Cecilia' },
  d : { name : 'Hugh' }
}

...其中slots[x][y]names'相关联密钥。

鉴于x和y是可以从0到10的输入,人们会写,以获取错误情况的名称和帐户:

let nameKey = (slots[x] || [])[y] //string or undefined
let name = (names[nameKey] || {}).name || ''

所以我在这里使用|| []|| {}之类的内容,以避免某些输入和空键出现错误。我听说通过使用FP套件我也可以更清洁地实现这一点。我应该使用Ramda(或任何其他FP套件)的哪些功能来实现它?

1 个答案:

答案 0 :(得分:3)

Ramda有pathOr

let slots = {
  7 : [ 'a', 'b', 'c' ],
  8 : [ 'd', 'e', 'f' ]
}
let names = {
  a : { name : 'Joe' },
  b : { name : 'Doe' },
  c : { name : 'Cecilia' },
  d : { name : 'Hugh' }
}

你会这样做:

let nameKey = R.pathOr(undefined, [x, y], slots);
//it'd be probably better to normalize it to always a string instead of undefined (but that's what you wrote)
let name = R.pathOr('', [nameKey, 'name'], names);