给出以下内容:
const cars = [
{
make: 'BMW',
model: 'E46',
year: 2002,
},
{
make: 'Toyota',
model: 'Altis',
year: 2009,
},
{
make: 'Chevrolet',
model: 'Camaro',
year: 1969,
},
{
make: 'Chevrolet',
model: 'Silverado',
year: 2002,
},
];
const filters = [
{
type: 'make',
payload: 'Chevrolet',
},
{
type: 'year',
payload: 2002,
},
];
如何filter
cars
使用类似下面的代码?
let filteredCars = [];
filters.forEach(filter => filteredCars = cars.filter(car => car.[filter.type] === car.[filter.payload]));
答案 0 :(得分:3)
使用filter
和some
来匹配任何过滤器
cars.filter((o) => filters.some((f) => o[f.type] == f.payload))
const cars = [ { make: "BMW", model: "E46", year: 2002 }, { make: "Toyota", model: "Altis", year: 2009 }, { make: "Chevrolet", model: "Camaro", year: 1969 }, { make: "Chevrolet", model: "Silverado", year: 2002 }, ];
const filters = [ { type: "make", payload: "Chevrolet" }, { type: "year", payload: 2002 }, ];
res = cars.filter((o) => filters.some((f) => o[f.type] == f.payload));
console.log(res);
或使用filter
和every
来匹配所有个过滤器
res = cars.filter((o) => filters.every((f) => o[f.type] == f.payload));
const cars = [ { make: "BMW", model: "E46", year: 2002 }, { make: "Toyota", model: "Altis", year: 2009 }, { make: "Chevrolet", model: "Silverado", year: 2002 }, { make: "Chevrolet", model: "Camaro", year: 1969 }, ];
const filters = [ { type: "make", payload: "Chevrolet" }, { type: "year", payload: 2002 }, ];
let res = cars.filter((o) => filters.every((f) => o[f.type] == f.payload));
console.log(res);
答案 1 :(得分:1)
首先,编写一个使单个汽车与单个过滤器匹配的谓词。
function carMatchesFilter(car, filter) {
return car[filter.type] === filter.payload;
}
如果我们想包括与所有过滤器匹配的汽车,我们将编写
const filteredCars = cars.filter(car =>
filters.every(filter => carMatchesFilter(car, filter))
);
如果我们要包含与任何个过滤器匹配的汽车,则可以编写
const filteredCars = cars.filter(car =>
filters.some(filter => carMatchesFilter(car, filter))
);
答案 2 :(得分:0)
我认为使用lodash
函数会很容易。
filteredCards = cars;
filters.forEach(function(element) {
filteredCards = _.filter(filteredCards, function(o) {
return o[element.type] == element.payload;
});
});
我希望这会有所帮助。