首页 > 解决方案 > 如何根据多个条件过滤我的数据?

问题描述

好的,所以我有一个对象数组,这是我要过滤的数据:

const posts = [
{
 hairday: '2',
 products: ['product1', 'product2', 'product3', 'product4'],
 rating: '2',
 drying: 'diffuser'
},
{
 hairday: '2',
 products: ['product6', 'product7', 'product8', 'product9'],
 rating: '4',
 drying: 'air dry'
},
{
 hairday: '3',
 products: ['product10', 'product11', 'product13', 'product14'],
 rating: '3',
 drying: 'air dry'
},
{
 hairday: '4',
 products: ['product15', 'product26', 'product37', 'product14'],
 rating: '5',
 drying: 'towel dry'
},
]

我想通过多个条件过滤上述数据。这是条件的示例对象:

{
 products: ['product1', 'product13'],
 hairday: ['2', '3'],
 drying: ['air dry', 'diffuser'],
 rating: []
}

所以我想获取post与每个数组中至少一个项目匹配的所有对象。

因此,过滤后的项目应具有 product1 OR product13 AND hairday 2 OR hairday 3 AND dry airdry ORdry diffuser 和任何评级。

最好的方法是什么?我的过滤器对象的结构是否最好?提前感谢<3

标签: javascriptarraysdata-structuresecmascript-6javascript-objects

解决方案


对于不需要手动列出键的更强大的解决方案,您可以使用Object.keys()迭代您的条件对象,然后将post数组中的各个对象与它进行比较:

const filtered = posts.filter(post => {
  const conditionKeys = Object.keys(conditions);
  const fulfillments = conditionKeys.map(k => {
    const condition = conditions[k];
    
    // If we encounter an empty array, then criteria is always met
    if (condition.length === 0) {
      return true;
    }
    
    // Enforces that as long as ONE subcondition is met (`OR`)
    return condition.filter(v => post[k].includes(v)).length > 0;
  });
  
  // Enforce that EVERY condition must be met (`AND`)
  // A condition is considered met as long as it is true
  return fulfillments.every(x => x);
});

当遍历单个条件(hairday、products 等)时,我们只是想检查您的对象是否包含一个或多个列出的值(即两个数组无论如何都相交)。如果有交点,则长度>0,否则为0。

请参阅下面的概念验证:

const posts = [{
    hairday: '2',
    products: ['product1', 'product2', 'product3', 'product4'],
    rating: '2',
    drying: 'diffuser'
  },
  {
    hairday: '2',
    products: ['product6', 'product7', 'product8', 'product9'],
    rating: '4',
    drying: 'air dry'
  },
  {
    hairday: '3',
    products: ['product10', 'product11', 'product13', 'product14'],
    rating: '3',
    drying: 'air dry'
  },
  {
    hairday: '4',
    products: ['product15', 'product26', 'product37', 'product14'],
    rating: '5',
    drying: 'towel dry'
  },
];

const conditions = {
  products: ['product1', 'product13'],
  hairday: ['2', '3'],
  drying: ['air dry', 'diffuser'],
  rating: []
};

const filtered = posts.filter(post => {
  const fulfillments = Object.keys(conditions).map(k => {
    const condition = conditions[k];
    
    // If we encounter an empty array, then criteria is always met
    if (condition.length === 0) {
      return true;
    }
    
    return condition.filter(v => post[k].includes(v)).length > 0;
  });
  
  return fulfillments.every(x => x);
});

console.log(filtered);


推荐阅读