我建立了一个包含 3 门类(class)的类(class)页面,
我想以一种方式构建它,所有类(class)都显示有购买按钮,类(class)信息是通过 products
集合从数据库中收集的。
然后我希望如果用户购买了类(class),而不是购买,将显示观看。
为此我有 2 个数组: 1)所有产品 2)用户购买的产品
现在我想比较它们,并从第一个数组中删除用户已经购买的所有产品。
我尝试在网上查找方法,但我根本不明白它们。
这是获取数组的函数:
const productRef = await db.collection("products").get();
const products = await productRef.docs.map(doc => {
return {
id: doc.id,
name: doc.data().name,
price: doc.data().price
};
});
console.log(products);
//[ { id: 'course1', name: 'Course 1', price: 25 },
{ id: 'course2', name: 'Course 2', price: 10 },
{ id: 'course3', name: 'Course 3', price: 30 } ]
if (user) {
const claims = res.locals.decodedClaims;
const uid = claims.uid;
const email = claims.email;
const userProductsRef = await db
.collection("users")
.doc(uid)
.collection("courses")
.get();
if (userProductsRef.docs.length > 0) {
const userProducts = userProductsRef.docs.map(doc => {
return { id: doc.id, name: doc.data().name };
});
console.log(userProducts);//[ { id: 'course1', name: 'Course 1' } ]
///COMPARE HERE the two arrays
}
}
现在我想通过 id 将产品与 userProducts 进行比较。
所以最终的预期结果应该是这样的:
products= [
{ id: 'course2', name: 'Course 2', price: 10 },
{ id: 'course3', name: 'Course 3', price: 30 } ];
userProducts= [ { id: 'course1', name: 'Course 1' } ]
谢谢!
最佳答案
您可以通过检查每个产品 ID 是否在 userProducts
数组中来过滤 products
数组:
const filteredProducts = products
.filter(prod => !userProducts.find(userProd => userProd.id === prod.id))
console.log(filteredProducts)
// [
// { id: 'course2', name: 'Course 2', price: 10 },
// { id: 'course3', name: 'Course 3', price: 30 }
// ]
我希望这就是您正在寻找的内容。
关于javascript - 比较两个数组,去掉重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57245198/