【问题标题】:Filter Array attribute from objects array based on another array [duplicate]根据另一个数组从对象数组中过滤数组属性[重复]
【发布时间】:2019-10-08 11:43:35
【问题描述】:

我想根据另一个数组过滤具有数组属性的对象数组:

[
  {
   id: 50,
   name: 'test1',
   countries: ['RO','GB'],
  }, {
    id: 51,
    name: 'test2',
    countries: ['DE', 'RO'],
  }, {
    id: 52,
    name: 'test3',
    countries: ['DE'],
  }
]

我想返回一个对象数组,可以按国家/地区数组过滤,这意味着如果我想按 1、2 个国家/地区过滤。

1. countries: ['RO']

2. countries: ['RO', 'DE'],

预期的输出是:

1.

[
  {
   id: 50,
   name: 'test1',
   countries: ['RO', 'DE' ,'GB'],
  }, {
    id: 51,
    name: 'test2',
    countries: ['DE', 'RO'],
  }
]

2.

[
  {
   id: 50,
   name: 'test1',
   countries: ['RO', 'DE' ,'GB'],
  }, {
    id: 51,
    name: 'test2',
    countries: ['DE', 'RO'],
  }, {
    id: 52,
    name: 'test3',
    countries: ['DE'],
  }
]

【问题讨论】:

    标签: javascript vue.js


    【解决方案1】:

    您可以使用filter()includes() 方法;

    var import1 = [
      {
       id: 50,
       name: 'test1',
       countries: ['RO','GB'],
      }, {
        id: 51,
        name: 'test2',
        countries: ['DE', 'RO'],
      }, {
        id: 52,
        name: 'test3',
        countries: ['DE'],
      }
    ];
    
    var export1 =  import1.filter(function(importz){
    	
    return importz.countries.includes("DE");
    });
    
    console.log(export1);

    【讨论】:

    • includes 应该期望一个字符串数组,了解如何过滤它们:array1.filter(object => object.countries.find(country => arrayOfCountries.includes(country)))跨度>
    【解决方案2】:

    使用此函数查找javascript数组中存在的多个值

    var containsAll = arr1.every(function (i) { return arr2.includes(i); });
    

    【讨论】:

      猜你喜欢
      • 2018-05-25
      • 2020-08-15
      • 2016-05-15
      • 2021-09-02
      • 1970-01-01
      • 2021-04-21
      • 2023-02-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多