【问题标题】:How to use lodash filter to find objects in a list that dont have a certain property如何使用 lodash 过滤器在列表中查找不具有特定属性的对象
【发布时间】:2019-12-13 21:29:07
【问题描述】:

我有一个看起来像这样的数组

{
  "id": "1",
  "name": "Test 1",
  "age": 23
},
{
  "id": "2",
  "name": "Test 2",
  "age": 62
},
{
  "id": "3",
  "name": "Test 3"
}

使用 lodash 过滤器,如何过滤未定义年龄的对象?如最后一个名为“Test 3”的项目

【问题讨论】:

    标签: filter lodash


    【解决方案1】:

    您可以使用_.filter() 删除项目,使用_.has() 检测它们是否具有age 属性:

    const arr = [{"id":"1","name":"Test 1","age":23},{"id":"2","name":"Test 2","age":62},{"id":"3","name":"Test 3"}]
    
    const result = _.filter(arr, o => _.has(o, 'age'))
    
    console.log(result)
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>

    或者使用lodash/fp生成函数:

    const fn = _.filter(_.has('age'))
    
    const arr = [{"id":"1","name":"Test 1","age":23},{"id":"2","name":"Test 2","age":62},{"id":"3","name":"Test 3"}]
    
    const result = fn(arr)
    
    console.log(result)
    <script src='https://cdn.jsdelivr.net/g/lodash@4(lodash.min.js+lodash.fp.min.js)'></script>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-03
      • 1970-01-01
      • 1970-01-01
      • 2015-02-27
      • 2013-02-13
      • 2022-06-11
      相关资源
      最近更新 更多