问题描述
我正在尝试为每个产品检查标签对象数组是否至少有一个节目标签。
const allProducts = this.products.forEach(product =>
product.tags.some(item => item.tagName !== 'shows'),)
数据样本:
Products: [
{
productId:...
productName: ...
tags:[
{
tagId:...
tagName:...
}
{
tagId:...
tagName:...
}
]
},{
productId:...
productName: ...
tags:[
{
tagId:...
tagName:...
}
{
tagId:...
tagName:...
}
]
}
]
似乎在 some() 之后它不起作用。出了什么问题,如何修复?
解决方法
首先, forEach
不返回任何内容。所以你应该改用 .filter
。
对于每个产品检查对象的标签数组是否至少有一个标签 的节目。
第二,条件应该是===
而不是!==
,此外,need return the true if all products are passing the some() not filter
==> 解决方案:
const allValidProducts = this.products.filter(product => product.tags.some(item => item.tagName === 'shows'));
const result = allValidProducts.length === this.products.length;
如您所见,.some
工作正常。
const array = [1,2,3,4,5];
console.log(array.some(element => element % 2 === 0));
// expected output: true
CORS_ORIGIN_ALLOW_ALL = True
如果过滤数组的长度保持不变,则所有产品都通过 const allProducts = this.products.filter(product => product.tags.some(item => item.tagName !== "shows")).length == allProducts.length;
。