【问题标题】:Mysql like query result using lodash from json array使用 lodash 来自 json 数组的 Mysql 查询结果
【发布时间】:2016-05-31 12:48:54
【问题描述】:

我的 JSON 看起来像这样

[{"id":"7","name":"hello","username":"hell7s692","password":"dAggzyFMnBXq3RjoTWoJ3ndBkGhyU6njT2ZPlNfXVV8+XU3vvrTaULUAbPcmsqgj1NpXOpzieKRXWox\/BVcYrA==","email":"hello@gmail.com","mobile_number":"7736527089","address":"hello","date":"24 Jan 2016 12:14:02","active":"1","commission":"5"},
{"id":"7","name":"hello","username":"hell7s692","password":"dAggzyFMnBXq3RjoTWoJ3ndBkGhyU6njT2ZPlNfXVV8+XU3vvrTaULUAbPcmsqgj1NpXOpzieKRXWox\/BVcYrA==","email":"hello@gmail.com","mobile_number":"7736527089","address":"hello","date":"24 Jan 2016 12:14:02","active":"1","commission":"5"}
]

从这里我想得到与类似查询中的条件匹配的新 json

即我想得到符合条件的json

获取名称以字母开头的所有json对象

类似mysql查询where name like he%

目前我只知道matches,但它返回的数组只有完全匹配。

var users = [
  { 'user': 'barney', 'age': 36, 'active': true },
  { 'user': 'fred',   'age': 40, 'active': false }
];

_.filter(users, _.matches({ 'age': 40, 'active': false }));
// → [{ 'user': 'fred', 'age': 40, 'active': false }]

这将只返回完全匹配。

【问题讨论】:

    标签: php json lodash


    【解决方案1】:

    您可以使用 _.startsWith() 来匹配您需要的前 n 个字符,而不是使用 _.matches()。例如,如果你想匹配以'he'开头的名字,你可以这样做:

    var result = [{
      name: 'hello'
    }, {
      name: 'healthy'
    }];
    
    _.filter(result, function(obj) {
      return _.startsWith(obj.name, 'he');
    });
    

    这应该两者都匹配。

    你也可以使用正则表达式来匹配它们:

    _.filter(result, function(obj) {
        return obj.name.search(/he/i) === 0;  // i = ignore case
    });
    

    '/he/i' 中的'i' 表示忽略大小写,所以这也会匹配 name = 'Hello'。

    search() 返回它找到的模式的第一个位置,如果没有找到它返回 -1。因此,如果您需要在字符串中的任意位置而不是从头开始查找模式,您可以检查 search() >= 0。所以

    _.filter(result, function(obj) {
        return obj.name.search(/he/i) >= 0;
    });
    

    将匹配 'hello'、'shell'、'healthy'、'the' 等

    【讨论】:

    • 收到此错误_.startsWith is not a function
    • 我认为 startsWith() 是 lodash 4.x。您可能正在使用 3.x。 'npm update lodash' 更新 lodash
    • 但是我的版本是4.3.0
    • 为了不区分大小写,您需要使用正则表达式,就像我在答案中的第二个解决方案一样。或者这样做 return _.startsWith(obj.name.toLowerCase(), 'he');
    • 我可以连接一个变量而不是字母吗?
    猜你喜欢
    • 1970-01-01
    • 2014-05-18
    • 2012-06-19
    • 2021-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多