如何在 js 中使用带有箭头函数的 2 个条件来过滤对象数组?

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

假设我有一个像这样的数组:

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

我想要一个箭头(过滤器)函数,returns 除了 taskType=type2 和 taskName=two 之外的所有项目。所以在这种情况下它只是 returns 第二项?

您可以尝试否定 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);

您可以使用 lodash 的 _.reject()。使用对象作为谓词,并定义要拒绝的属性和值:

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>