搜索对象数组以获取键值匹配

时间:2014-11-27 22:23:34

标签: jquery object search key

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

我发现这code符合我的需要,但它可以显示所有数据,只显示有搜索到的密钥的第一个。更多解释一下,如果我添加另一个搜索“PIR000”的相同代码密钥的人,第一个将显示在outpout 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);

1 个答案:

答案 0 :(得分:0)

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