我有两个
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},
];
我需要过滤掉activeStatusFilter,以便应删除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返回,但不是。有人可以帮我解决为什么这种方法不奏效或更优化的方法
答案 0 :(得分:1)
您可以使用Set
来做到这一点:
const labels = new Set(statusFilter.map(v => v.label));
const filtered = activeStatusFilter.filter(v => labels.has(v.label));
答案 1 :(得分:1)
您可以通过组合filter
和find
来获得所需的输出
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)
您需要:
filter()
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);