【问题标题】:How to make fuzzy search using Lodash java-script library?如何使用 Lodash java-script 库进行模糊搜索?
【发布时间】:2017-01-18 15:45:12
【问题描述】:

我想使用查询字符串从对象数组中进行模糊搜索。 搜索可以嵌套在搜索对象中,如下例所示;

var data = [ 
              {
                "id":"1",
                "name":"Ali",
                "BOD":"29/10/2055",
                "type":"primary",
                "email":"b@v.com",
                "mobile":"0100000000",
                "notes":["note1" ,"note2" ,"note3"]
              },
               {
                "id":"2",
                "name":"Tie",
                "BOD":"29/10/2055",
                "type":"primary",
                "email":"b@v.net",
                "mobile":"0100000000",
                "notes":["note4" ,"note5" ,"note6"]
              }
  ];


   function search(query){
     // search code go here
     
     }

   // search examples
   search('.net'); //expected data[1]
   search('ali');  //expected data[0]
   search('0110'); //expected data[0],data[1]

【问题讨论】:

  • 为什么'ali'会得到两个结果?
  • “模糊搜索”是什么意思?您希望query 与任何对象值匹配吗?
  • 返回匹配的逻辑是什么?另见Javascript fuzzy search that makes sense
  • @guest271314 这更符合我对模糊搜索的预期。
  • @NinaScholz 抱歉我现在修好了

标签: javascript lodash fuzzy-search


【解决方案1】:

我做了一个简单的解决方案,它不是最理想的,但它有效。 这样做没有嵌套搜索的模糊搜索分数。

var data = [ 
              {
                "id":"1",
                "name":"Ali",
                "BOD":"29/10/2055",
                "type":"primary",
                "email":null,
                "mobile":"010100000000",
                "notes":["note1" ,"note2.nett" ,"note3"]
              },
               {
                "id":"2",
                "name":"Tie",
                "BOD":"29/10/2055",
                "type":"primary",
                "email":"b@v.net",
                "mobile":"0100000000",
                "notes":["note4" ,"note5" ,"note6"]
              }
  ];

    /**
     * query: query string to match with
     * dataArray: data array variable, array or opject to search it
     **/
   function search(query,dataArray){
     // search code go here
     //console.log(query);
     var matched = [];
     //init null values
     if(!dataArray)dataArray={};
     if(!query)query='';
     dataArray.forEach(function(obj,index){
        for(var key in obj){
          if(!obj.hasOwnProperty(key) || !obj[key]) continue;
          if(obj[key].toString().indexOf(query) !== -1)
            {
              matched.push(obj );
            } 
        }
     });
     return matched ;      
     }

   // search examples .
  console.log("found",search('.net',data).length);//expected data[0] data[1]
  console.log("found",search('Ali',data).length);//expected data[0]
  console.log("found",search('0116',data).length);//expected data[0],data[1] 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-20
    • 1970-01-01
    • 2016-01-18
    • 2021-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多