过滤数组并匹配至少一个条件

时间:2019-06-27 17:27:09

标签: javascript arrays vue.js vuejs2 lodash

我想解决以下问题:我想使用Vue.js和lodash(或纯JavaScript)按特定条件过滤数组。

我的对象

  • 我得到了Items的列表。每个项目都包含(可选)categories
  • 对象Car可以具有category

对象Items

"data": [
    {
      "id": 1,
      "title": "Item 1",
      "categories": [
        {
          "id": 4,
          "title": "category 4",
          "description": "",
        },
        {
          "id": 5,
          "title": "category 5",
          "description": "",
        }
      ]
    },
    {
      "id": 2,
      "title": "Item 2",
      "categories": []
    },
    {
      "id": 3,
      "title": "Item 3",
      "categories": []
    }
  ]

对象Car

{
  "category": {
    "id": 5,
    "title": "category 5",
    "description": ""
  },
  "title": "Test"
}

我的目标

我只想显示至少通过以下规则之一的Items

  • Item至少有一个categorycategory的{​​{1}}匹配
  • Car设置了 Item

我的方法

我正在使用category值来过滤computed

this.items

当前结果:

computed: { filteredItems: function () { let vm = this; return _.filter (this.items, function (item) { return _.includes (item.categories, vm.car.category ); }); } }, 始终为空。

2 个答案:

答案 0 :(得分:3)

您需要对categories进行另一级检查,因为您需要针对其中的每个项目进行测试。使用常规javascript,您可以使用some()进行操作,如果有任何一项匹配,则返回true。

let data = [{"id": 1,"title": "Item 1","categories": [{"id": 4,"title": "category 4","description": "",},{"id": 5,"title": "category 5","description": "",}]},{"id": 2,"title": "Item 2","categories": []},{"id": 3,"title": "Item 3","categories": []}]
let  car = {"category": {"id": 5,"title": "category 5","description": ""},"title": "Test"}

let filtered = data.filter(item => !item.categories || item.categories.length === 0 ||  item.categories.some(cat=> cat.id === car.category.id))
console.log(filtered)

答案 1 :(得分:1)

使用lodash,您需要类似的东西

result = _.filter(data, ({categories}) =>
    _.isEmpty(categories) ||
    _.some(categories, cat => cat.id === car.category.id))

如果您想比较整个类别对象,而不仅仅是ID,那么

_.filter(data, ({categories}) => 
    _.isEmpty(categories) || 
    _.some(categories, cat => _.isEqual(cat, car.category)
    ))