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"
}
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?
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.
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!
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With