首页 > 解决方案 > 对象过滤的嵌套数组在 JS 中返回 undefined

问题描述

我正在尝试为每个产品检查标签对象数组是否至少有一个节目标签。

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() 之后它不起作用。出了什么问题,如何解决?

标签: javascriptarraysecmascript-6javascript-objectsecmascript-5

解决方案


首先, 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


推荐阅读