过滤Javascript对象数组与另一对象数组

2022-02-21 00:00:00 arrays filter javascript

我有列表

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']}
];

解决方案

可以使用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);

相关文章