假设我有一个数据结构,如:
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套件)的哪些功能来实现这一目标?
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);