【问题标题】:Filter array and match at least one condition过滤数组并匹配至少一个条件
【发布时间】:2019-11-09 18:28:30
【问题描述】:

我想解决以下问题:我想使用 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 至少有一个与Car 中的category 匹配的category
  • Item没有 category 设置

我的方法

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

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

当前结果:

filteredItems 始终为空。

【问题讨论】:

  • 您可以仅使用 ID 进行比较,假设每个类别都是唯一的。您的函数的返回值类似于return !item.categories.length || _.includes(item.categories.map(category => category.id), vm.car.category.id);

标签: javascript arrays vue.js vuejs2 lodash


【解决方案1】:

您需要对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)

【讨论】:

    【解决方案2】:

    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)
        ))
    

    【讨论】:

    • 非常感谢。有没有一种优雅的方法来检查是否设置了car.category?我会把它包装到if 这样的支票上:if (typeof vm.car.category !== 'undefined'){...}
    • @SPQRInc:在第二个 sn-p 中,isEqual 会处理这个问题。无需检查。
    猜你喜欢
    • 2019-06-21
    • 1970-01-01
    • 2019-03-11
    • 1970-01-01
    • 1970-01-01
    • 2021-01-21
    • 1970-01-01
    • 1970-01-01
    • 2013-05-29
    相关资源
    最近更新 更多