如何过滤出两个对象数组之间的数据

时间:2020-06-29 13:35:49

标签: javascript

我有两个

var statusFilter = [
  {label: '1', checked: false},
  {label: '3', checked: false},
  {label: '4', checked: false},
  {label: '5', checked: false},
];

var activeStatusFilter = [
  {label: '1', checked: true},
  {label: '2', checked: true},
];

我需要过滤掉ac​​tiveStatusFilter,以便应删除statusStatusFilter中不存在的activeStatusFilter中的任何元素。 因此,该函数的结果应为[{label:'1',checked:true}],因为状态过滤器中不存在label:'2'。

我已经写了一个函数来做同样的事情,但是它总是返回一个空数组。

const z = activeStatusFilter.filter( activeStatus =>
{
  let found = false;
  statusFilter.forEach(status => {
    console.log( activeStatus );
    console.log( "status", status )
    found =  ( activeStatus.label === status.label )
    return found
  })
  return found;
} )

我觉得在found = ( activeStatus.label === status.label )的forEach中,它应该从forEach返回,但不是。有人可以帮我解决为什么这种方法不奏效或更优化的方法

6 个答案:

答案 0 :(得分:1)

您可以使用Set来做到这一点:

const labels = new Set(statusFilter.map(v => v.label));
const filtered = activeStatusFilter.filter(v => labels.has(v.label));

答案 1 :(得分:1)

您可以通过组合filterfind来获得所需的输出

const z = activeStatusFilter.filter( activeStatus => {
  return statusFilter.find( s => activeStatus.label === s.label)
})

答案 2 :(得分:1)

var statusFilter = [
  {label: '1', checked: false},
  {label: '3', checked: false},
  {label: '4', checked: false},
  {label: '5', checked: false},
];

var activeStatusFilter = [
  {label: '1', checked: true},
  {label: '2', checked: true},
];

const result = activeStatusFilter.filter(x => {
       return (statusFilter.findIndex( y => y.label === x.label) > -1)
})

答案 3 :(得分:1)

您在这里!

var statusFilter = [
  {label: '1', checked: false},
  {label: '3', checked: false},
  {label: '4', checked: false},
  {label: '5', checked: false},
];

var activeStatusFilter = [
  {label: '1', checked: true},
  {label: '2', checked: true},
];
var set = new Set();
statusFilter.forEach(status =>  set.add(status.label));

activeStatusFilter =activeStatusFilter.filter(active => set.has(active.label));

console.log(activeStatusFilter);

答案 4 :(得分:1)

var statusFilter = [
  {label: '1', checked: false},
  {label: '3', checked: false},
  {label: '4', checked: false},
  {label: '5', checked: false},
];

var activeStatusFilter = [
  {label: '1', checked: true},
  {label: '2', checked: true},
];
res=activeStatusFilter.filter(x=>statusFilter.some(y=>y.label==x.label))
console.log(res)

答案 5 :(得分:1)

您需要:

  1. filter()
  2. some()

Set的替代方法。这是一个工作示例:

var statusFilter = [
  {label: '1', checked: false},
  {label: '3', checked: false},
  {label: '4', checked: false},
  {label: '5', checked: false},
];

var activeStatusFilter = [
  {label: '1', checked: true},
  {label: '2', checked: true},
];

var result = activeStatusFilter.filter(k=>statusFilter.some(l=>l.label==k.label));

console.log(result);