如何根据多个条件筛选数据?

aamkag61  于 2021-09-13  发布在  Java
关注(0)|答案(2)|浏览(320)

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

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以及干燥空气干燥或干燥扩散器和任何等级。
最好的办法是什么?我的筛选器对象是否以最佳方式构造?提前感谢

0s7z1bwu

0s7z1bwu1#

对于不需要手动列出密钥的更健壮的解决方案,您可以使用 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);
mkh04yzy

mkh04yzy2#

我可以这样编写一个相当通用的版本:

const findMatches = (filters, xs) => 
  xs .filter (x => Object .entries (filters) .every (([name, vals]) =>
    vals.length == 0 ||
    (Array .isArray (x [name])
      ? x [name] .some (val => vals .includes (val))
      : vals .includes (x [name]))
  ))

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 filters = {products: ['product1', 'product13'], hairday: ['2', '3'], drying: ['air dry', 'diffuser'], rating: []}

console .log (findMatches (filters, posts))
.as-console-wrapper {min-height: 100% !important; top: 0}

代码对帖子、产品、发日等一无所知。它只是根据条件对象过滤对象列表。
不过,这有点我不喜欢。空数组的特殊处理( ratings )让人觉得这是个错误的设计。我建议,如果没有任何匹配值,就不要将其包含在条件对象中。因此,我们将删除“ratings1”以获得公正的结果

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

这对我来说更有逻辑意义,因为其他条件都说,本质上,对象中的值必须是给定列表中的一个(或者在数组的情况下,元素中的一个必须是给定列表中的一个)。空的 ratings 物体破坏了它。
这将使代码稍微简化为

const findMatches = (filters, xs) => 
  xs .filter (x => Object .entries (filters) .every (([name, vals]) =>
    Array .isArray (x [name])
      ? x [name] .some (val => vals .includes (val))
      : vals .includes (x [name])
  ))

这些版本中存在一些低效之处。我们去拿 x [name] 每人两次 x ,这可能不是什么大问题,但我们也会 Object .entriesfilters 每一个价值。如果该函数最终成为应用程序中的瓶颈,您可能需要修复它们。此版本将清除这两个问题,并允许您针对给定的一组条件创建可重用函数:

const findMatches = (filters) => {
  const toMatch = Object .entries (filters)
  return (xs) => 
    xs .filter (x => toMatch .every (([name, vals]) => {
      const val = x [name]
      return Array .isArray (val)
        ? val .some (val => vals .includes (val))
        : vals .includes (val)
    }))
}

你会用稍微不同的方式来称呼它:

const myFilter = findMatches (filters)
// ... later
console .log (myFilter (posts))

但我不会费心,除非这成为应用程序瓶颈,这似乎不太可能。第一个版本,或者理想的第二个版本更干净。

相关问题