0

如果它们存在于另一个数组中,我试图从一个数组中过滤掉记录。Products 是我的初始数组,其中包含我的所有产品, productsToDelete 包含 2 个产品作为示例。我想要实现的是,如果 productsToDelete 有一个产品已经存在于 Products 中,它必须过滤掉它。我面临的问题是没有唯一的键或 ID,所以我无法比较数组。是否可以将数组中的对象与另一个对象进行比较。

代码:

const [products, setProducts] = useState<Product[]>([]);
const [productsToDelete, setProductsToDelete] = useState<Product[]>([]);


setProducts((products) =>
      products.filter((product) => product !== productsToDelete.map(val => val))
    );

产品数组的属性:

category: string;
subCategory: string;
name: string;
quantity: number;
price: number;
4

1 回答 1

1

我同意其他评论:对于这种情况,您应该有一个唯一的 ID。但是,从技术上讲,如果两个数组之间的项目字面上相同,则可以直接比较它们。就像是:

setProducts((products) =>
    products.filter((product) => productsToDelete.every(val => val !== product))
);
于 2020-10-05T19:27:38.180 回答