【问题标题】:How to filter an array of objects with another array, based on values in the arrays of objects's property? [duplicate]如何根据对象属性数组中的值用另一个数组过滤对象数组? [复制]
【发布时间】:2021-07-15 15:59:31
【问题描述】:

我有一个名为配置文件的对象数组: [{id: 0, 子类别: ['A', 'B', 'C']}, {id: 1, 子类别: ['A']}]

我有一个名为 tags 的数组:['B']

我想过滤配置文件,只保留标签中具有值的配置文件。在这种情况下,id = 0 的配置文件将被保存。

这是我迄今为止尝试过的,但似乎没有用:

      let filtered_profiles = profiles.filter((profile) =>
        tags.includes(profile.subcategories)
     );

【问题讨论】:

  • let filtered_profiles = profiles.filter((profile) => profile.subcategories.some(sub => tags.includes(sub)));

标签: javascript


【解决方案1】:

这是我的方法。如果配置文件子类别至少包含一个标签,则将其推送到结果对象中。

let profiles = [{id: 0, subcategories: ['A', 'B', 'C']}, 
                     {id: 1, subcategories: ['A']}];

let tags = ['B'];
let result = [];

profiles.forEach(function (p){
let copied = false;
  tags.forEach(function (t) {
    if (p.subcategories.includes(t) && !copied) {
      result.push(p);
      copied = true;
    }
  })
});

console.log(result);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-02-23
    • 2019-09-30
    • 2021-09-02
    • 2020-08-15
    • 2022-11-01
    • 2018-12-25
    • 2021-10-24
    • 2022-11-30
    相关资源
    最近更新 更多