繁体   English   中英

自动完成功能可按属性搜索json对象

[英]Autocomplete functionality to search through json object by attribute

假设我有以下json对象,其中包含有关一组人员的信息。

data=[{id:2, fname:"bob", lname:"roberts", common_name:null, email:"sideshowbob@email.com", telephone:"555-555-5555", street:"333 Street St", city:"Salt Lake City", state:"UT", country:null, zip:"99999", dynamid:null, notes:null, director:false, contractor:false, contractor_need_agreement:false, shareholder:false, shares_held:0, company_id:1, created_at:"2016-02-23T10:15:09.339Z", updated_at:"2016-02-23T10:15:09.339Z", officer:false, snapshot:null, sign_term_voting:false, drag_liquidation_approval:false, rofr_consenter:false, investor_councel:false, ir_insured:false, issuer_signing_officer:false, issuer_registered_agent:false, issuer_councel:false, rep_lead_investor:false, rep_investor:false, rep_founder:false}, 
      {id:1, fname:"John", lname:"Smith", common_name:null, email:"john.smith@email.com", telephone:"555-555-5555", street:"333 Street St", city:"Salt Lake City", state:"UT", country:null, zip:"99999", dynamid:null, notes:null, director:false, contractor:false, contractor_need_agreement:false, shareholder:false, shares_held:0, company_id:1, created_at:"2016-02-23T10:15:09.327Z", updated_at:"2016-02-23T10:15:09.327Z", officer:false, snapshot:null, sign_term_voting:false, drag_liquidation_approval:false, rofr_consenter:false, investor_councel:false, ir_insured:false, issuer_signing_officer:false, issuer_registered_agent:false, issuer_councel:false, rep_lead_investor:false, rep_investor:false, rep_founder:false}]

现在,我想在文本框中实现某种自动完成功能,该文本框中搜索每个人的姓名(即fname+" "+lname )以查找匹配项。 找到匹配项后,它要么返回找到匹配项的人,要么返回该人的ID。

我在开始上遇到了一些麻烦。 我想我可以将其写出来,在那里我可以使用keyup触发对象的循环,显示与字符串匹配的名称,并在单击其中的一个时返回相应的索引,但这似乎是我在重新发明轮子。

有没有一种有效/最佳实践的方法来实现这种功能?

从这个typeahead.js演示在这里

jsfiddle上的完整代码:

var substringMatcher = function(strs) {
  return function findMatches(q, cb) {
    var matches, substringRegex;

    matches = [];

    substrRegex = new RegExp(q, 'i');

    $.each(strs, function(i, str) {
      var fullname = str.fname + " " + str.lname
            console.log(fullname);

      if (substrRegex.test(fullname)) {
        matches.push(fullname);
      }
    });

    cb(matches);
  };
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM