我有一系列事件对象,如下所示:
{
date: "2015-06-03T19:29:01.000Z",
description: "Test",
talks: [{
author: "Nick",
tags: ["tag1", "tag2", "tag3"]
}]
}
我只想从这个对象中获取标签,所以我像这样使用Ramda:
let eventTags = pipe(prop('talks'), map(prop('tags')), flatten, uniq)
...
eventTags(event); //and call function on event object
但是有时事件对象看起来像这样:
{
date: "2015-06-03T19:29:01.000Z",
description: "Test",
talks: [{
author: "Nick",
tags: null
}]
}
所以我在[null]
数组中得到了eventTags
,但我希望得到一个空数组。那么如何过滤null?
答案 0 :(得分:2)
我会提倡使用镜头访问tags
并使用 Ramda 和Sanctuary将undefined
视为Maybe Nothing
的解决方案
const x = [{
date: "2015-06-03T19:29:01.000Z",
description: "Test",
talks: [{
author: "Nick",
tags: ["tag1", "tag2", "tag3"]
}]
}, {
date: "2015-06-03T19:29:01.000Z",
description: "Test",
talks: [{
author: "Nick",
tags: null
}]
}]
const viewTalks = S.compose ( S.toMaybe ) (
R.view ( R.lensProp( 'talks' ) )
)
const viewTags = S.compose ( S.toMaybe ) (
R.view ( R.lensProp ( 'tags' ) )
)
const allTalkTags = S.map ( S.pipe ( [
S.map ( viewTags ),
S.justs,
R.unnest
] ) )
const allTalksTags = S.pipe( [
S.map ( S.pipe( [
viewTalks,
allTalkTags
] ) ),
S.justs,
R.unnest,
R.uniq
] )
// outputs: ['tag1', 'tag2', 'tag3']
allTalksTags ( x )
答案 1 :(得分:2)
如果接收到null或未定义的值,您可以在此处使用R.defaultTo([])
来创建一个返回空数组的函数,否则将值传递给未修改的。
const eventTags = pipe(
prop('talks'),
map(pipe(prop('tags'), defaultTo([]))),
flatten,
uniq
)
答案 2 :(得分:1)
通过MatíasFidemraizer帮助我将eventTags
功能更改为:
const viewTags = talk => !!talk.tags ? talk.tags : [];
export let eventTags = pipe(prop('talks'), map(viewTags), flatten, uniq)