有没有一种方法可以使用通配符属性来过滤对象数组?

时间:2020-08-13 03:03:22

标签: javascript arrays object

给出以下内容:

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]));

3 个答案:

答案 0 :(得分:3)

使用filtersome来匹配任何过滤器

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);

或使用filterevery来匹配所有个过滤器

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;
    });
});

我希望这会有所帮助。