问题
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