【问题标题】:lodash to filter and sortlodash 过滤和排序
【发布时间】:2019-06-11 17:52:18
【问题描述】:

我正在使用 lodash 来拟合数组,但是它区分大小写,我也不知道如何查询多个字段。

举个例子:

let arr = [
  { a: 'John', b: 'Smith' },
  { a: 'Penny', b: 'Eversmith' },
  { a: 'Smithers', b: 'Jones' },
  { a: 'Jane', b: 'Doe' }
];

我如何过滤这个,如果有人通过“Smith”查询,我会得到以下信息,假设 Smith 出现在 3 个句子和小写的记录中?

[
  { a: 'John', b: 'Smith' },
  { a: 'Penny', b: 'Eversmith' },
  { a: 'Smithers', b: 'Jones' }
]

或者,如果在 js 中不使用 lodash 很简单,那么我也可以。

【问题讨论】:

    标签: javascript node.js lodash


    【解决方案1】:

    不再需要 Lodash 进行过滤或映射,因为 ES5 (2009) 将 filtermap 添加到 Array.prototype

    如果您知道属性的名称,只需检查它们:

    const result = arr.filter(({a, b}) => a.includes(searchStr) || b.includes(searchStr));
    

    如果不是并且您想检查所有属性,您可以使用Object.valuessome(另一个 ES5 东西):

    const result = arr.filter(entry => Object.values(entry).some(val => val.includes(searchStr));
    

    Object.values 是 ES2017+,但很容易填充。

    我在那里也使用了Array.prototype.includes,它是 ES2016(同样,很容易填充)。

    【讨论】:

      【解决方案2】:

      您可以简单地使用filtersome 并将所有值设置为单个大小写以匹配以实现不区分大小写

      let arr = [
        { a: 'John', b: 'Smith' },
        { a: 'Penny', b: 'Eversmith' },
        { a: 'Smithers', b: 'Jones' },
        { a: 'Jane', b: 'Doe' }
      ];
      
      let findName = (arr,name) => arr.filter(val=>{
        return Object.values(val).some(v=> v.toLowerCase().includes(name.toLowerCase()))
      })
      
      console.log(findName(arr,'Smith'))

      【讨论】:

        【解决方案3】:

        使用 lodash 的解决方案看起来与使用 ES6 的解决方案没有什么不同:

        let arr = [ { a: 'John', b: 'Smith' }, { a: 'Penny', b: 'Eversmith' }, { a: 'Smithers', b: 'Jones' }, { a: 'Jane', b: 'Doe' } ];
        
        let search = (a, s) => 
          _.filter(a, x => _(x).values().some(y => _.includes(_.toLower(y), _.toLower(s)))) 
        
        console.log(search(arr, 'Smith'))
        console.log(search(arr, 'doe'))
        <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

        使用 ES6 会短一些:

        let arr = [ { a: 'John', b: 'Smith' }, { a: 'Penny', b: 'Eversmith' }, { a: 'Smithers', b: 'Jones' }, { a: 'Jane', b: 'Doe' } ];
        
        let search = (a, s) => a.filter(x => 
          Object.values(x).some(y => y.toLowerCase().includes(s.toLowerCase())))
        
        console.log(search(arr, 'Smith'))
        console.log(search(arr, 'doe'))

        【讨论】:

          猜你喜欢
          • 2017-01-28
          • 1970-01-01
          • 2019-04-12
          • 2021-01-19
          • 2011-11-27
          • 1970-01-01
          • 1970-01-01
          • 2020-07-14
          • 2020-05-27
          相关资源
          最近更新 更多