我和LeftyX的對話似乎並沒有在jqGrid中做到這一點,所以我創建了一個用於在數組中的對象之間執行「JOIN」的方法。功能如下:
function joinJSONFK (entities, fkProperties, fkLookupArrays) {
function findValInAry(ary, idfield, value) {
for (var i = 0; i < ary.length; i++) {
if (value == ary[i][idfield]) {
return ary[i];
}
}
return null;
};
function applyFKProperties(entity, fkProperties, fkLookupArrays) {
for (var i = 0; i < fkProperties.length; i++) {
entity[fkProperties[i] + "Source"] = findValInAry(fkLookupArrays[i], fkProperties[i], entity[fkProperties[i]]);
}
return entity;
}
var entityary = [];
if (!entities instanceof Array) {
entities = applyFKProperties(entities);
return entities[0];
}
else {
for (var i = 0; i < entities.length; i++) {
entities[i] = applyFKProperties(entities[i], fkProperties, fkLookupArrays);
}
return entities;
}
}
您可以按如下方式使用它:
userRoleData = joinJSONFK(result, ["SysRoleId", "BranchId"], [GlobalRoles, GlobalBranches]);
其中 「結果」 是JSON的數組具有以下格式的對象:
[{"entityHashCode":null,"BranchId":25,"SysRoleId":1,"SysUserId":1},
{"entityHashCode":null,"BranchId":25,"SysRoleId":2,"SysUserId":1},
{"entityHashCode":null,"BranchId":26,"SysRoleId":1,"SysUserId":1]
而且[「SysRoleId」,「BranchId」]是需要「JOINED」的外鍵數組,而[GlobalRoles,GlobalBranches]是包含外鍵的「查找」數據的數組。
GlobalRoles會是這個樣子:
[{"Name":"Admin","SysRoleId":1,"Description":"Some description"},
{"Name":"Role 2","SysRoleId":2,"Description":"Some description"},
{"Name":"A new role","SysRoleId":3,"Description":"Some description"},
{"Name":"Another Role","SysRoleId":4,"Description":"Some description"}]
而且GlobalBranches會是這個樣子:
[{"BranchName":"Branch 25","BranchId":25,"Description":"describe the branch"},
{"BranchName":"Branch 26","BranchId":26,"Description":"describe the branch"},
{"BranchName":"Branch 27","BranchId":27,"Description":"describe the branch"}]
調用函數時, 「userRoleData」 將樂這樣的事情後:
[{"entityHashCode":null,"BranchId":25,"SysRoleId":1,"SysUserId":1, "SysRoleIdSource":{"Name":"Admin","SysRoleId":1,"Description":"Some description"}, "BranchIdSource":{"BranchName":"Branch 25","BranchId":25,"Description":"describe the branch"}},
{"entityHashCode":null,"BranchId":25,"SysRoleId":2,"SysUserId":1}, "SysRoleIdSource":{"Name":"Role 2","SysRoleId":2,"Description":"Some description"}, "BranchIdSource":{"BranchName":"Branch 25","BranchId":25,"Description":"describe the branch"}},
{"entityHashCode":null,"BranchId":26,"SysRoleId":1,"SysUserId":1, "SysRoleIdSource":{"Name":"Admin","SysRoleId":1,"Description":"Some description"}, "BranchIdSource":{"BranchName":"Branch 26","BranchId":26,"Description":"describe the branch"}}]
這種方式有一個很好的結構化的對象集合。
雖然這個方法很有效,但我對它的答案感到滿意,如果任何人都可以提供其他不涉及改變WCF的建議 - 因爲它不能改變 - 我會很樂意將其作爲正確答案刪除。 – pedrodg 2011-06-02 07:00:46