How to use filter array of objects by 2 conditions with an arrow function in js? [duplicate]

≯℡__Kan透↙ 提交于 2020-01-14 07:01:21

问题


Suppose I have an array like:

  const items=[{
        "taskType": "type2",
        "taskName": "two",
        "id": "19d0da63-dfd0-4c00-a13a-cc822fc81298"
      },
      {
        "taskType": "type1",
        "taskName": "two",
        "id": "c5385595-2104-409d-a676-c1b57346f63e"
      }]

I want to have an arrow (filter) function that returns all items except for where taskType=type2 and taskName=two. So in this case it just returns the second item?


回答1:


You can try negating the condition in Array.prototype.filter()

const items=[{
        "taskType": "type2",
        "taskName": "two",
        "id": "19d0da63-dfd0-4c00-a13a-cc822fc81298"
      },
      {
        "taskType": "type1",
        "taskName": "two",
        "id": "c5385595-2104-409d-a676-c1b57346f63e"
      }]

var res = items.filter(task => !(task.taskType == 'type2' && task.taskName == 'two'));

console.log(res);



回答2:


You can use lodash's _.reject(). Use an object as a predicate, and define the properties and values to reject by:

const items= [{
  "taskType": "type2",
  "taskName": "two",
  "id": "19d0da63-dfd0-4c00-a13a-cc822fc81298"
},
{
  "taskType": "type3",
  "taskName": "two",
  "id": "19d0da63-dfd0-4c00-a13a-cc822fc81298"
},
{
  "taskType": "type1",
  "taskName": "two",
  "id": "c5385595-2104-409d-a676-c1b57346f63e"
}]

const result = _.reject(items, { taskType: "type2", taskName: "two" });

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>


来源:https://stackoverflow.com/questions/54761482/how-to-use-filter-array-of-objects-by-2-conditions-with-an-arrow-function-in-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!