使用两个条件从对象数组过滤数据

时间:2019-10-02 10:44:51

标签: javascript arrays arraylist

我有一个对象数组。每个对象中包含属性类别名称和categoryId以及子类别列表(即array)。我要根据名称和subcategoryList值两者过滤数据。这是我的示例数组

var statesWithFlags = [
    { subCategoriesList: ['Badges and dentures', 'Cerezens', 'Dental implants'], categoryId: 1, categoryName: "Dental" },
    { subCategoriesList: ['Badges and dentures44', 'Dental implants'], categoryId: 2, categoryName: "Dermatology" },
    { subCategoriesList: ['Badges and dentures', 'Cerezens', 'Dental implants222'], categoryId: 3, categoryName: "Eye" },
    { subCategoriesList: ['Badges and dentures', 'Cerezens', 'Dental implants', 'Cerezens'], categoryId: 4, categoryName: "Ayurvedic" }
  ]

当前,我正在使用类似的东西。这仅适用于categoryName属性。我也希望对类别列表进行修改。

this.statesWithFlags.filter(v => v.categoryName.toLowerCase().indexOf(term.toLowerCase()) > -1)).slice(0, 10))

1 个答案:

答案 0 :(得分:1)

检查.some中的subCategoriesList是否具有要搜索的字符串,或者categoryName是否具有您搜索的字符串:

const termLower = term.toLowerCase();
this.statesWithFlags.filter(v => (
  v.subCategoriesList.some(subCat => subCat.toLowerCase().includes(termLower))
  || v.categoryName.toLowerCase().includes(termLower)
))
  .slice(0, 10);