使用来自JSON数组的lodash的MySQL喜欢的查询结果 [英] Mysql like query result using lodash from json array

查看:68
本文介绍了使用来自JSON数组的lodash的MySQL喜欢的查询结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的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

From this i want to get the new json that matches the condition in like query

即我想获取带有条件的json

ie i want to get the json with the condition

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

相似的mysql查询where name like he%

Similar mysql query where name like he%

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

Currently i know about only matches but it returns the array with only exact match.

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 }]

这将仅返回完全匹配的结果.

This will returns with only exact match.

推荐答案

您可以使用_.startsWith()来匹配所需的前n个字符,而不是使用_.matches().例如,如果要匹配以"he"开头的名称,则可以执行以下操作:

Instead of using _.matches(), you can use _.startsWith() to match the first n-characters you need to. For example, if you want to match name starting with 'he', you can do something like this:

var result = [{
  name: 'hello'
}, {
  name: 'healthy'
}];

_.filter(result, function(obj) {
  return _.startsWith(obj.name, 'he');
});

这应该两者都匹配.

您还可以使用正则表达式来匹配它们:

You can also use regular expression to match them:

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

'/he/i'中的'i'表示忽略大小写,因此也将匹配name ='Hello'.

'i' in '/he/i' means ignore case, so this will match name = 'Hello' also.

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

search() returns the 1st position of the pattern it found, it returns -1 if not found. So if you need to find a pattern anywhere in a string instead of starting from the beginning, you can check for search() >= 0. So

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

将匹配"hello","shell","healthy","the"等

will match 'hello', 'shell', 'healthy', 'the', and etc

这篇关于使用来自JSON数组的lodash的MySQL喜欢的查询结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆