【问题标题】:Search object array for a key value match在对象数组中搜索键值匹配
【发布时间】:2014-11-27 22:23:33
【问题描述】:

我是 jQuery 新手,我需要帮助, 我想使用键值显示对象数组中的一些数据。

我发现这个code 符合我的需要,但它可以显示所有数据,只显示第一个具有搜索键的数据。为了进一步解释,如果我添加另一个具有相同代码键的人搜索“PIR000”,第一个将显示在输出 div 中。

我需要显示我需要的所有数据,

谢谢

    <span id="output"></span>


    var Person = function(code, name) {
    this.code = code;
    this.name = name;
    };
    var people = [
        new Person("ABC123", "Tooth Fairy"),
        new Person("PIR000", "Jack Sparrow2"),
        new Person("PIR000", "Jack Sparrow3"),
        new Person("DEF456", "Santa Claus"),
        new Person("PIR000", "Jack Sparrow"),
        new Person("XYZ987", "Easter Bunny")
        ];


    var utils = {};
    // Could create a utility function to do this
    utils.inArray = function(searchFor, property) {
        var retVal = -1;
        var self = this;
        for(var index=0; index < self.length; index++){
            var item = self[index];
            if (item.hasOwnProperty(property)) {
                if (item[property].toLowerCase() === searchFor.toLowerCase()) {
                    retVal = index;
                    return retVal;
                }
            }
        };
        return retVal;
    };

    // or we could create a function on the Array prototype indirectly
    Array.prototype.inArray = utils.inArray;

    // let's use the prototype for now
    var i = people.inArray("PIR000", "code");
    $('#output').text(people[i].name);

【问题讨论】:

    标签: jquery object search key


    【解决方案1】:

    http://jsfiddle.net/cmLegqdw/1/

    var Person = function (code, name) {
        this.code = code;
        this.name = name;
    };
    var people = [
    new Person("ABC123", "Tooth Fairy"),
    new Person("PIR000", "Jack Sparrow2"),
    new Person("PIR000", "Jack Sparrow3"),
    new Person("DEF456", "Santa Claus"),
    new Person("PIR000", "Jack Sparrow"),
    new Person("XYZ987", "Easter Bunny")];
    
    //find people with the given code
    function findPerson(codeF)
    {
        //variable with search results
        var rezultA=[];
    
        //loop through variable peapole
        for (var p in people) {
            var code=people[p].code;//get code
            var name=people[p].name;//get name
    
            //check for equal code
            if(code==codeF) rezultA.push(name);
       }
       return  rezultA;
    }
    
    
    var prersonFind=findPerson('PIR000');
    
    document.getElementById('output').innerHTML=prersonFind.join('<br/>');
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-01
      • 2015-07-06
      • 1970-01-01
      • 1970-01-01
      • 2014-08-26
      相关资源
      最近更新 更多