Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I index by multiple items in an Array or Object using JavaScript/jQuery?

Background

I have an Array of data in a result object returned by an Ajax call. The data looks like this:

{ Name="User1 Name1", FirstName="User1", Id="005400000001234567", more...}
{ Name="User2 Name1", FirstName="User2", Id="005400000001234568", more...}

Where each item looks like this:

{
    Id:"005400000001234567",
    Name:"User Name",
    FirstName:"User",
    LastName:"Name",
    Title:"Manager"
}

Question

I want to be able to retrieve data either by Id (returning a single user) or by Title (returning an array of users). What would be the best way to go about doing that using JavaScript or jQuery?

Example

Here's what I've attempted so far:

function GetAllUsers()
{
    AllUsersById = new Object();

    MyClass.MyAjaxMethod(function(result,event) {
        if(result) { 
            j$(result).each(function(index,item)
            {
                AllUsersById[item.Id] = item;
            });
        }
    });
}

The code I have above is great for indexing by Id, but I'm not sure what to do for Title.

Additional Details

Also, by the way, there are about 1000 records, and I need this to be fairly efficient. (This is one of the reasons I'm getting the data right away, when the document is ready. I'm not an expert on JavaScript or jQuery efficiency, though. Let me know if you have a better way.)

Any ideas? Thanks in advance!

like image 628
Matt K Avatar asked Feb 14 '12 20:02

Matt K


1 Answers

Seems like you're looking for .grep(). Using .grep you could create a generic function that would filter:

function findInJson (json, key, value) {
    return $.grep(json, function (obj) {
        return obj[key] == value;
    });
}

// With your data getting a specific user by id
findInJson(yourJSON, "Id", "005400000001234567");

// Getting a set of users by title
findInJson(yourJSON, "Title", "Manager");
like image 86
sinemetu1 Avatar answered Oct 11 '22 15:10

sinemetu1