javascript 过滤具有多个条件的对象数组。

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript 过滤具有多个条件的对象数组。相关的知识,希望对你有一定的参考价值。

/**
 * Filters an array of objects with multiple criteria.
 *
 * @param  {Array}  array: the array to filter
 * @param  {Object} filters: an object with the filter criteria as the property names
 * @return {Array}
 */
function multiFilter(array, filters) {
  const filterKeys = Object.keys(filters);
  // filters all elements passing the criteria
  return array.filter((item) => {
    // dynamically validate all filter criteria
    return filterKeys.every(key => !!~filters[key].indexOf(item[key]));
  });
}
let products = [
  { name: "A", color: "Blue", size: 50 },
  { name: "B", color: "Blue", size: 60 },
  { name: "C", color: "Black", size: 70 },
  { name: "D", color: "Green", size: 50 },
];

// the value of each key is an array with the values to filter
let filters = {
  color: ["Blue", "Black"],
  size: [70, 50]
};

// filter the products array by color: blue and black
// and also by size: 70 and 50
var filtered = multiFilter(products, filters);

console.info('Filtered:');
console.log(filtered);

/* expected
[
  { name: "A", color: "Blue", "size": 50 },
  { name: "C", color: "Black", "size": 70 }
]
*/

以上是关于javascript 过滤具有多个条件的对象数组。的主要内容,如果未能解决你的问题,请参考以下文章

javascript过滤数组多个条件

基于多值对象过滤javascript对象数组

如何过滤具有多个条件的托管对象实体

通过在嵌套的对象数组中查找多个条件来过滤数组

javascript 根据选择条件过滤数组对象。

过滤具有相同 ID 和给定条件的对象的 json 数组