我怎样才能基于多个条件过滤我的数据?

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

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或Product13和Hairday 2或Hairday 3以及风干或烘干扩散器和任何额定值。

解决此问题的最佳方式是什么?我的过滤对象的结构是最好的吗? 提前感谢<;3


解决方案

对于不需要手动列出键的更健壮的解决方案,您可以使用Object.keys()迭代您的Criteria对象,然后将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);

相关文章