[英]How do I index by multiple items in an Array or Object using JavaScript/jQuery?
我在Ajax調用返回的結果對象中有一個數據Array。 數據如下所示:
{ Name="User1 Name1", FirstName="User1", Id="005400000001234567", more...}
{ Name="User2 Name1", FirstName="User2", Id="005400000001234568", more...}
每個項目看起來像這樣:
{
Id:"005400000001234567",
Name:"User Name",
FirstName:"User",
LastName:"Name",
Title:"Manager"
}
我希望能夠通過Id (返回單個用戶)或Title (返回用戶數組)來檢索數據。 使用JavaScript 或 jQuery進行此操作的最佳方法是什么?
這是我到目前為止所做的嘗試:
function GetAllUsers()
{
AllUsersById = new Object();
MyClass.MyAjaxMethod(function(result,event) {
if(result) {
j$(result).each(function(index,item)
{
AllUsersById[item.Id] = item;
});
}
});
}
我上面的代碼很適合用Id編制索引,但我不知道該怎么做Title。
順便說一下,大約有1000條記錄 ,我需要這個記錄才能相當高效 。 (這是我在文檔准備就緒時立即獲取數據的原因之一。但我不是JavaScript或jQuery效率方面的專家。如果你有更好的方法,請告訴我。)
有任何想法嗎? 提前致謝!
好像你在尋找.grep() 。 使用.grep你可以創建一個可以過濾的泛型函數:
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");
創建一個構造函數,相對於封裝此數據的類,您可以要求它按標題或ID查找用戶。 要進行快速查找,您可以創建兩個查找表 - 一個用於id,另一個用於標題。 假設一個合適的散列實現,查找可以平均在O(1)
完成。 初始計算是O(n),但查找速度更快。 它還使用了更多的空間,因為我們正在創建兩個額外的地圖。 對於1000個對象,這不是問題。 同樣,如果您要進行更多查找,這種方法會更快。
這是一個簡單的實現。
function Users(users) {
this.idMap = {};
this.titleMap = {};
this.users = users;
var me = this;
users.forEach(function(user) {
this.idMap[user.Id] = this.idMap[user.Id] || [];
this.idMap[user.Id].push(user);
this.titleMap[user.Title] = this.titleMap[user.Title] || [];
this.titleMap[user.Title].push(user);
}.bind(this));
}
Users.prototype.findByTitle = function(title) {
return this.titleMap[title];
};
Users.prototype.findById = function(id) {
return this.idMap[id];
};
要使用它,請創建一個Users
對象,向其傳遞AJAX響應,然后使用findById
和findByTitle
方法進行查詢。
var users = new Users(responseData);
users.findById("1");
users.findByTitle("SomeTitle");
查看一個工作示例 。
我認為這應該有效。 沒有你的數據,我真的無法測試它。
function GetAllUsers()
{
AllUsersById = new Object();
AllUsersByType = new Object();
MyClass.MyAjaxMethod(function(result,event) {
if(result) {
j$(result).each(function(index,item)
{
// By Id
AllUsersById[item.Id] = item;
// By Type
if (!AllUsersByTitle[item.Title]) {
AllUsersByTitle[item.Title] = new Array();
}
AllUsersByType[item.type].push() = item;
});
}
});
}
如果您可以控制返回的數據,那么使用以下格式生成數據會更好:
var allUsers=[
{"005400000001234567":{
Name:"User Name",
FirstName:"User",
LastName:"Name",`
Title:"Manager"
}}
,{"005400000001234568":{
Name:"User2 Name2",
FirstName:"User2",
LastName:"Name2",
Title:"Manager2"
}}
/*..etc.. */
];
這樣就可以避免GetAllUsers
(構建上面的數組)中的循環( $(result).each()
)。 可以通過構建表單的第二個數組來有效地執行按title
搜索:
var byTitle=["title1":[0,1], "title1":[0,1], /*etc*/];
如您所見,每個標題都有一個allUsers
的索引列表。 然后你只需:
var allManagers = [];
for(var i in byTitle["Manager"]) allManagers.push(allUsers[i]);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.