Mysql like query result using lodash from json array

浪子不回头ぞ 提交于 2019-12-02 12:27:31

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');
});

This should match both.

You can also use regular expression to match them:

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

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

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;
});

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!