简体   繁体   中英

How to search array keys in JavaScript/jQuery using indexOf

I have an array members . This array has a name as the index (eg "John Smith") and an array with "degree" and "id", like so:

数组

I have a search that fires on keyup action. It is supposed to search through the member names (the index) and then output the name of any matching members to the console:

function memberSearch(){
    var $input = $("#guestsearch>input");
    var val = $input.val();
    console.log(val);

    $.each(members, function(i,v){
        if(i.indexOf(val)>-1){
            console.log(members[i]);
        }
    })
}

However, this doesn't output anything except the search value val . Even if the $.each function is just console.log(i) , nothing outputs.

If I manually type console.log(members) into console, the screenshot from above is the result.

members is populated by this segment of a function:

$.each(json.response.data[0].members, function(i,v){
    var m = json.response.data[0].members[i];
    var name = m.name;
    if(name.typeof!=="undefined"&&name!=""&&name!=null&&name.length>0){
        members[name] = [];
        members[name]["degree"] = m.degree;
        members[name]["id"] = m.id;
    }
})

How can I make this search work?

If members is an object, which it looks like with the key/value pairs, you can use Object.keys(objVariable) to get the keys of an object to loop over and do your comparison/regex logic on.

Object.keys(members).forEach(function(name){
    if (/* logic to match on name */) {
        console.log(members[name]);
    }
});

Otherwise if members is an array containing those objects...

var matchingUsers = members.filter(function(){
    var username = Object.keys(this)[0];

    return (/* match username to whatever */);
});

Then matchingUsers would be an array containing all the users that passed your criteria.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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