代码之家  ›  专栏  ›  技术社区  ›  Sangram Badi

如何使用lodash过滤像sqlin子句这样的条件数组?

  •  0
  • Sangram Badi  · 技术社区  · 4 年前

    我试图用lodash过滤数组中的数据。我试图像SQL-IN子句一样进行过滤。

    ex: - select * from Test where id IN (2,4,5,67); 
    

    JSON:

    storedData = [
        {
            "id" : 1,
            "name" : "ABC"
        },
        {
            "id" : 2,
            "name" : "XYZ"
        },
        {
            "id" : 3,
            "name" : "BVX"
        },
        {
            "id" : 4,
            "name" : "OOO"
        }
    ]
    

    搜索条件:

    [2,4,5,67]
    

    output = [
        {
            "id" : 2,
            "name" : "XYZ"
        },
        {
            "id" : 4,
            "name" : "OOO"
        }
    ]
    

    下面是我试图实现的代码

    output = _.filter(storedData, (value) => {
        return value.id == 2 || value.id == 4 || value.id == 5 || value.id == 67
    });
    

    你能帮我怎样在子句中过滤吗?

    2 回复  |  直到 4 年前
        1
  •  3
  •   Nick Parsons Felix Kling    4 年前

    您可以使用 intersectionWith ,它允许您提供回调,并将保留回调返回的第一个数组中的所有元素 true 因为。

    参见以下示例:

    const storedData = [ { "id" : 1, "name" : "ABC" }, { "id" : 2, "name" : "XYZ" }, { "id" : 3, "name" : "BVX" }, { "id" : 4, "name" : "OOO" } ];
    const search = [2,4,5,67];
    
    const res = _.intersectionWith(storedData, search, (o, n) => o.id === n); 
    console.log(res);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>
        2
  •  2
  •   hgb123    4 年前

    .includes

    _.filter(storedData, (value) => _.includes(criteria, value.id))
    

    const storedData = [
      {
        id: 1,
        name: "ABC",
      },
      {
        id: 2,
        name: "XYZ",
      },
      {
        id: 3,
        name: "BVX",
      },
      {
        id: 4,
        name: "OOO",
      },
    ]
    
    const criteria = [2, 4, 5, 67]
    
    const output = _.filter(storedData, (value) => _.includes(criteria, value.id))
    
    console.log(output)
    <script src="https://cdn.jsdelivr.net/npm/lodash@4.17.20/lodash.min.js"></script>