根据另一个数组从对象数组过滤Array属性

时间:2019-10-08 11:43:35

标签: javascript vue.js

我想基于另一个数组来过滤具有数组属性的对象数组:

[
  {
   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'],
  }
]

2 个答案:

答案 0 :(得分: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);

答案 1 :(得分:0)

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

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