douxin1884 2016-02-19 03:49
浏览 92
已采纳

Mysql喜欢使用来自json数组的lodash查询结果

I have JSON look like this

[{"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"}
]

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

ie i want to get the json with the condition

get all the json object with name start with a letter

Similar mysql query where name like he%

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.

  • 写回答

1条回答 默认 最新

  • dsa88885555 2016-02-19 07:53
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 树莓派控制机械臂传输命令报错,显示摄像头不存在
  • ¥15 前端echarts坐标轴问题