根据另一个数组中的键值对象从数组中删除对象的最有效方法

Most efficient way to remove objects from array based on key value objects in another array

给定 excludes 和 items 数组,我想 return 来自不包含与 excludes 中的键、值对对象对应的键、值对的项的对象数组。除了使用嵌套 for 循环之外,还有更好的解决方法吗?

const excludes = [{key: "color", value: "Red"}, {key: "age", value:12}, {key:"score", value: 75}];

const items = [{color: "Red", score: 30, age: 12}, {color: "Blue", score: 100, age: 20}, {color: "Red", score: 75, age: 30}];

//Expected output: [{color: "Blue", score: 100, age: 20}]

使用filter()过滤items数组。过滤条件根据 excludes 数组检查项目的每个属性。如果 none 个匹配,则该项目包含在结果中。

const excludes = [{key: "color", value: "Red"}, {key: "age", value:12}, {key:"score", value: 75}];

const items = [{color: "Red", score: 30, age: 12}, {color: "Blue", score: 100, age: 20}, {color: "Red", score: 75, age: 30}];

let result = items.filter(item =>
  !Object.entries(item).some(([key, value]) => 
    excludes.find(e => e.key = key && e.value == value)));
console.log(result);

您可以按如下方式使用Array#filter, as suggested by @Barmar, in combination with Array#every

const excludes = [{key: "color", value: "Red"}, {key: "age", value:12}, {key:"score", value: 75}],
      items = [{color: "Red", score: 30, age: 12}, {color: "Blue", score: 100, age: 20}, {color: "Red", score: 75, age: 30}],
      
      output = items.filter(
          item => excludes.every(
              ({key,value}) => item[key] !== value
          )
      );

console.log( output );
//OUTPUT: [{color: "Blue", score: 100, age: 20}]