javascript TypeScript -检查Object是否具有数组中的所有值

iecba09b  于 2023-04-28  发布在  Java
关注(0)|答案(1)|浏览(166)

我正在尝试筛选一个对象,该对象仅在属性具有筛选数组中的所有值时才返回。这就是代码:

const getFilteredProducts = ()=>{
        const filterBrands:string[] = [];
        const filterGender:string[] = [];

        FilterState().brand.map(brand =>{
            if(brand.checked == true){
                filterBrands.push(brand.brand);
            }
        });
        FilterState().gender.map(brand =>{
            if(brand.checked == true){
                filterGender.push(brand.gender);
            }
        })
        products?.map((product)=>{
            if(Object.values(product.Brand).includes(filterBrands[0]) && Object.values(product.Gender).includes(filterGender[0])){
                console.log(product);
            }

        })
    }

我首先循环通过品牌过滤器,如果过滤器被勾选,它会将其添加到品牌过滤器数组。例如- Nike被勾选,因此Nike被添加到过滤器阵列。然后,我对性别过滤器做同样的操作,然后我循环遍历对象,我想检查对象是否具有数组中的品牌名称,并且与性别相同。如何将includes(filterBrands[0])更改为检查所有阵列的内容?如果这说得通的话。

dbf7pr2w

dbf7pr2w1#

function arrayContainsArray(superset, subset) {
  return subset.every((value) => superset.includes(value));
}

const getFilteredProducts = () => {
  const filterBrands = FilterState()
                          .brand.filter((brand) => brand.checked === true)
                          .map((brand) => brand.brand);

  const filterGender = FilterState()
                          .gender.filter((gender) => gender.checked === true)
                          .map((gender) => gender.gender);

  const result = products.filter((product) => arrayContainsArray(Object.values(product.Brand), filterBrands) && arrayContainsArray(Object.values(product.Gender), filterGender));

  for (const p of result) {
    console.log(p);
  }
};

相关问题