让我们假设有一个名为cars的对象数组:
var cars = [
{color: 'Black', horsePower: 120, type: 'suv'},
{color: 'Red', horsePower: 90, type: 'cabriolet'},
{color: 'Yellow', horsePower: 200, type: 'cabriolet'},
{color: 'Black', horsePower: 350, type: 'suv'}
];
我想过滤通过多个条件的该数组。因此,我创建了一个过滤器对象。
var filters = {
color: ['Black', 'Red'],
horsePower: [90],
type: []
};
我尝试过的是:
var output = cars.filter((elem) => {
for (var key in filters) {
if (filters[key].length == 0 || filters[key].indexOf(elem[key]) < 0) {
return false;
}
}
return true;
});
console.log(output);
我期望得到的结果是汽车的第二个索引,但是我得到一个空数组。
我在做什么错了?
答案 0 :(得分:1)
您的原始过滤器将为type
属性查找带有空数组的汽车。而且您的车上没有一个物体具有该功能。这应该起作用。
var cars = [
{color: 'Black', horsePower: 120, type: 'suv'},
{color: 'Red', horsePower: 90, type: 'cabriolet'},
{color: 'Yellow', horsePower: 200, type: 'cabriolet'},
{color: 'Black', horsePower: 350, type: 'suv'}
];
var filters = {
color: ['Black', 'Red'],
horsePower: [90]
};
var output = cars.filter((elem) => {
for (var key in filters) {
if (filters[key].length == 0 || filters[key].indexOf(elem[key]) < 0) {
return false;
}
}
return true;
});
console.log(output);
答案 1 :(得分:1)
如果filter[key].length == 0
是您return false
,则您可能希望将条件更改为:
if(filter[key].length && !filter[key].includes(elem[key]))
答案 2 :(得分:1)
这就是我将使用Array.prototype.filter
的方式:
const cars = [
{color: 'Black', horsePower: 120, type: 'suv'},
{color: 'Red', horsePower: 90, type: 'cabriolet'},
{color: 'Yellow', horsePower: 200, type: 'cabriolet'},
{color: 'Black', horsePower: 350, type: 'suv'}
];
const filters = {
color: ['Black', 'Red'],
horsePower: [90],
type: []
};
let filteredCars = cars.filter(car => {
for (const prop in filters) {
if (filters[prop].length && !filters[prop].includes(car[prop])) return false;
}
return true;
});
console.log(filteredCars);