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

问题描述 投票:0回答:1

假设我有一个数据结构,如:

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套件)的哪些功能来实现这一目标?

javascript ramda.js
1个回答
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);
© www.soinside.com 2019 - 2024. All rights reserved.