I have array of event objects, looks like:
{
date: "2015-06-03T19:29:01.000Z",
description: "Test",
talks: [{
author: "Nick",
tags: ["tag1", "tag2", "tag3"]
}]
}
I want to take only tags from this object, so I use Ramda like this:
let eventTags = pipe(prop('talks'), map(prop('tags')), flatten, uniq)
...
eventTags(event); //and call function on event object
But there is cases when event object looks like this:
{
date: "2015-06-03T19:29:01.000Z",
description: "Test",
talks: [{
author: "Nick",
tags: null
}]
}
So I got [null]
in my eventTags
array, but I want to get an empty array instead. So how can I filter null?
I have array of event objects, looks like:
{
date: "2015-06-03T19:29:01.000Z",
description: "Test",
talks: [{
author: "Nick",
tags: ["tag1", "tag2", "tag3"]
}]
}
I want to take only tags from this object, so I use Ramda like this:
let eventTags = pipe(prop('talks'), map(prop('tags')), flatten, uniq)
...
eventTags(event); //and call function on event object
But there is cases when event object looks like this:
{
date: "2015-06-03T19:29:01.000Z",
description: "Test",
talks: [{
author: "Nick",
tags: null
}]
}
So I got [null]
in my eventTags
array, but I want to get an empty array instead. So how can I filter null?
-
No need to use Ramda, just do
event.talks.tags || []
. – str Commented Apr 10, 2018 at 8:57 - My mistake - talks is array of objects – Mad Max Commented Apr 10, 2018 at 9:04
3 Answers
Reset to default 4You could utilise R.defaultTo([])
here to create a function that returns an empty array if null or undefined values are received, otherwise passing the value through unmodified.
const eventTags = pipe(
prop('talks'),
map(pipe(prop('tags'), defaultTo([]))),
flatten,
uniq
)
I would advocate for a solution that could access tags
using lenses and treat undefined
as Maybe Nothing
using both Ramda and Sanctuary
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.pose ( S.toMaybe ) (
R.view ( R.lensProp( 'talks' ) )
)
const viewTags = S.pose ( 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 )
Click to run a working sample
With Matías Fidemraizer help I changed my eventTags
function to this:
const viewTags = talk => !!talk.tags ? talk.tags : [];
export let eventTags = pipe(prop('talks'), map(viewTags), flatten, uniq)
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744961961a4603443.html
评论列表(0条)