I've hit a snag after a few hours -- wondered if a fresh minded developer can just review the below, the code is simplied to show the problem.
I am filtering a property value on an array of objects, and cross referencing that property with an array which has matching keys, and boolean values to control if it should be factored into the filter.
However my result is returning all 3 objects, despite the console.log seeming to evaluate correctly. Any ideas?
Many thanks...
var data = [{
"id": 1,
"status": "new",
},
{
"id": 2,
"status": "rejected",
},
{
"id": 3,
"status": "changed",
}
];
var filter = {
"new": true,
"rejected": false,
"changed": true
}
var result = data.filter(function(item) {
var arr = [];
Object.keys(filter).forEach(function(key) {
if (item.status === key && filter[key] === true) {
console.log('---')
console.log('item.status', item.status)
console.log('key', key)
console.log('filter[key]', filter[key])
console.log('---')
arr.push(item);
}
});
return arr;
});
You're making this a bit more complicated than you need to. The function passed to filter()
should return a boolean — you're returning an array.
You can simply filter with the lookup on the filter
array, which will either return false
or undefined
, in which case you filter it out, or true
, in which case you keep it..
var data = [{
"id": 1,
"status": "new",
},
{
"id": 2,
"status": "rejected",
},
{
"id": 3,
"status": "changed",
}
];
var filter = {
"new": true,
"rejected": false,
"changed": true
}
var result = data.filter(item => filter[item.status])
console.log(result)