【问题标题】:how to filter an array on condition like SQL IN clause using lodash?如何使用 lodash 在 SQL IN 子句等条件下过滤数组?
【发布时间】:2020-09-09 04:06:01
【问题描述】:

我正在尝试使用 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
});

你能帮我如何过滤像 IN 子句吗?

【问题讨论】:

    标签: javascript ecmascript-6 lodash


    【解决方案1】:

    您可以使用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】:

      使用.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>

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-10-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-09-02
        • 2023-03-27
        • 2016-06-22
        相关资源
        最近更新 更多