过滤数组并匹配至少一个条件 [英] Filter array and match at least one condition

查看:168
本文介绍了过滤数组并匹配至少一个条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想解决以下问题:我想在某些条件下使用Vue.js和lodash(或纯JavaScript)过滤数组.

I'd like to solve the following problem: I would like to filter an array by certain conditions with Vue.js and lodash (or pure JavaScript).

  • 我得到了 Items 的列表.每个项目都包含(可选)类别.
  • 对象 Car 可以具有类别.
  • I got a list of Items. Each item contains (optional) categories.
  • The object Car can have a category.
"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": []
    }
  ]

对象汽车

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

我的目标

我只想显示那些通过了至少一个规则的 Items :

  • Item 具有至少一个与 Car
  • category 匹配的 category
  • Item 没有 类别设置
  • The Item has at least one category that matches the category of the Car
  • The Item has no category set

我正在使用 computing 值来过滤 this.items :

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

当前结果:

filteredItems 始终为空.

推荐答案

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

You need to do one more level of checking on categories because you need to test against each item inside it. With regular javascript you can do that with some() which will return true if any of the items match.

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)

这篇关于过滤数组并匹配至少一个条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆