代码之家  ›  专栏  ›  技术社区  ›  Breezer

从对象生成语句

  •  -1
  • Breezer  · 技术社区  · 2 年前

    嗨,我有一个最大的大脑冻结,我试图通过存储在对象中的键和值对来过滤数组,我目前的问题是它只是递归地过滤,就像它是一个and运算符一样,但我希望它过滤,就像每个语句都是可选的,就像OR运算符在每个过滤器之间一样。

    这是我目前拥有的代码

     Object.entries(filterCond).forEach(([key, value])=> {
              filtered = filtered.filter(function(){ 
                  return jQuery(this).data(key).includes(+value)
              })
    })
    

    其中filterCond包含数据属性的键值对,如果有不清楚的地方,请随时询问我会尽我所能重新详细说明

    1 回复  |  直到 2 年前
        1
  •  1
  •   CertainPerformance    2 年前

    滤器 filtered 这样每个值都有一个只调用一次的回调,在回调中,检查 .some filterCond 满足。

    你的 this 也错误地引用了当前回调中的窗口-使用回调的参数引用了正在迭代的元素。

    const elementsWithAtLeastOneMatch = filtered.filter(
      element => Object.entries(filterCond).some(
        ([key, value]) => $(element).data(key)?.includes(+value)
      )
    );
    

    演示:

    const filterCond = {
      prop: '3',
      prop2: 'another',
    };
    const elements = [...$('.foo')];
    const elementsWithAtLeastOneMatch = elements.filter(
      element => Object.entries(filterCond).some(
        ([key, value]) => $(element).data(key)?.includes(+value)
      )
    );
    console.log(elementsWithAtLeastOneMatch);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="foo" data-prop="'3'"></div>
    <div class="foo" data-prop="'4'"></div>
    <div class="foo"></div>

    但是,如果您要查找的值在数据属性中,那么就没有必要依赖像jQuery这样的大型库来获得如此简单的东西。

    const elementsWithAtLeastOneMatch = filtered.filter(
      element => Object.entries(filterCond).some(
        ([key, value]) => element.dataset[key]?.includes(+value)
      )
    );