0

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

Array

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?

7
  • where are you defining members? Commented May 7, 2016 at 16:31
  • @JordanHendrix Outside of any function - var members = [];, then it is populated by another function Commented May 7, 2016 at 16:32
  • can you log members in the the member search? Commented May 7, 2016 at 16:33
  • members is an Array? Seems like you're describing a plain Object. Where's the code? Are you trying to put non-index names on an Array? If so, $.each will ignore them. Commented May 7, 2016 at 16:33
  • @squint Apologies - I've changed the question. In that case, how can I search the indexes if they are strings (member names) using indexOf? Commented May 7, 2016 at 16:34

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.