我对我与 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"}}]
这种方式有一个结构良好的对象集合。