【问题标题】:Complex collection filter with lodash带有 lodash 的复杂收集过滤器
【发布时间】:2017-01-11 19:20:21
【问题描述】:

我有一个嵌套的 JSON 结构,如下所示:

[
  {
    name: 'some name',
    type: 'type1',
    collection: ['one', 'two', 'three']
  },
  {
    name: 'another name',
    type: 'type1',
    collection: ['one', 'two']
  },
  {
    name: 'third name',
    type: 'type2',
    collection: ['two']
  }
]

我正在尝试编写一个 lodash _.filter 语句(尽可能简单),我可以在其中过滤类型等字符串属性,但也可以过滤数组属性,如集合检查它是否包含某些值。例如,我想查找所有具有 typetype1 的对象,并且具有包含值 onetwocollection 数组。

这种类型的东西有简写吗,还是我坚持编写一个函数来做一些typeof 体操来确定属性值类型,然后进行相应的比较?

【问题讨论】:

  • _.filter 有一个使用 _.matches 的简写,如果你提供一个对象作为谓词。如果库中存在或不存在某些内容,该文档包含所有需要回答的内容。
  • 主题其实并不那么复杂
  • 我的意思是“复杂”,因为它是一个嵌套的数据结构。

标签: javascript filter lodash


【解决方案1】:

使用_.filter 的简写_.matches 在过滤时执行部分深度比较:

var array = [{"name":"some name","type":"type1","collection":["one","two","three"]},{"name":"another name","type":"type1","collection":["one","two"]},{"name":"third name","type":"type2","collection":["two"]}];
    
var filtered = _.filter(array, { 
  type: 'type1', 
  collection: ['one', 'two'] 
});

console.log(filtered);
<script src="https://cdn.jsdelivr.net/lodash/4.15.0/lodash.min.js"></script>

【讨论】:

  • 天哪,我是不是觉得自己很蠢。我发誓我试过了,但没用。
【解决方案2】:

你可以这样做。很简单。

_.filter(arr, item => {
    const hasCollection = item.collection && item.collection.indexOf('one') > -1 && item.collection.indexOf('two') > -1;
    return item.type === 'type1' && hasCollection;
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-02-25
    • 2018-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多