代码之家  ›  专栏  ›  技术社区  ›  Mad Max

Ramda筛选器空属性

  •  0
  • Mad Max  · 技术社区  · 7 年前

    我有一个事件对象数组,看起来像:

    {
        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 数组,但我想得到一个空数组。那么如何过滤空值呢?

    3 回复  |  直到 7 年前
        1
  •  3
  •   Scott Christopher    7 年前

    您可以利用 R.defaultTo([]) 这里创建一个函数,如果接收到null或未定义的值,则返回空数组,否则通过未修改的传递值。

    const eventTags = pipe(
      prop('talks'),
      map(pipe(prop('tags'), defaultTo([]))),
      flatten,
      uniq
    )
    
        2
  •  2
  •   Matías Fidemraizer    7 年前

    我主张一种可以访问 tags 使用镜片和治疗 undefined Maybe Nothing 使用两者 拉姆达 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.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 )
    

    Click to run a working sample

        3
  •  1
  •   Mad Max    7 年前

    在Matas Fidemraizer的帮助下,我改变了 eventTags 功能:

    const viewTags = talk => !!talk.tags ? talk.tags : [];
    
    export let eventTags = pipe(prop('talks'), map(viewTags), flatten, uniq)