首页 > 解决方案 > lodash.js 选择像 mysqls `in`

问题描述

我正在使用 lodash.js 过滤我的 json 值。我在 Lodash 中需要类似 Mysqls “in”函数的东西。

json value:
[
{id:1,customer:5},{id:2,customer:6},{id:3,customer:6},{id:2,customer:7}
]

我想"customer in(6,7)"在 lodash 中选择。我该怎么做?

标签: javascriptmysqljsonlodash

解决方案


您可以在集合上使用 lodashes过滤器功能。

const input = '[{"id":1,"customer":5},{"id":2,"customer":6},{"id":3,"customer":6},{"id":2,"customer":7}]';

const mysqlIn = (json, array) => {
  const data = JSON.parse(json);
  let ans = _.filter(data, function(x) {
    return array.includes(x.customer);
  });
  return ans;
}

console.log(mysqlIn(input, [6,7]));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>


推荐阅读