使用另一个对象数组过滤Javascript对象数组

时间:2016-10-17 11:40:02

标签: javascript arrays filter

我有清单

var list = [
  {name: 'Hello', ads: true, pas: ['Av', 'Sd', 'Qr']},
  {name: 'Fre', ads: false, pas: ['Sd', 'Bc']},
  {name: 'Nat', ads: false, pas: ['Bc', 'Mo', 'Rr']},
  {name: 'Bor', ads: true, pas: ['Bo', 'Be', 'De']},
  {name: 'Arg', ads: true, pas: ['Ar', 'Na', 'Br']},
];

和数组过滤器

var filter = [
 'Sd','Be'
];

我尝试使用filter但不过滤。

list
  .filter(function(ls) {
    return ls.pas
      .filter(function(p){
        return filter.indexOf(p) > -1;
      })
  })

我的预期输出

[
  {name: 'Hello', ads: true, pas: ['Av', 'Sd', 'Qr']},
  {name: 'Fre', ads: false, pas: ['Sd', 'Bc']},
  {name: 'Bor', ads: true, pas: ['Bo', 'Be', 'De']}
];

2 个答案:

答案 0 :(得分:3)

您可以使用some()检查当前对象的pas数组中的任何元素是否在filter数组中。

var list = [
  {name: 'Hello', ads: true, pas: ['Av', 'Sd', 'Qr']},
  {name: 'Fre', ads: false, pas: ['Sd', 'Bc']},
  {name: 'Nat', ads: false, pas: ['Bc', 'Mo', 'Rr']},
  {name: 'Bor', ads: true, pas: ['Bo', 'Be', 'De']},
  {name: 'Arg', ads: true, pas: ['Ar', 'Na', 'Br']},
];

var filter = [
 'Sd','Be'
];

var result = list.filter(function(e) {
  return e.pas.some(function(a) {
    return filter.indexOf(a) != -1
  })
})

console.log(result);

答案 1 :(得分:0)

使用es6看起来很不错:

const list = [
   {name: 'Hello', ads: true, pas: ['Av', 'Sd', 'Qr']},
   {name: 'Fre', ads: false, pas: ['Sd', 'Bc']},
   {name: 'Nat', ads: false, pas: ['Bc', 'Mo', 'Rr']},
   {name: 'Bor', ads: true, pas: ['Bo', 'Be', 'De']},
   {name: 'Arg', ads: true, pas: ['Ar', 'Na', 'Br']},
],
filter = ['Sd','Be']

list.filter(a=>a.pas.some(a=>filter.includes(a))