我希望使用JQuery使用JSON创建角色和权限的表矩阵。该表应具有复选框,如果该值存在于JSON中,则应检查角色和权限映射单元格。
这是我的JSON格式:
var obj = [
{
"WidgetID": 1,
"WidgetName": "Widget 1 ",
"ProjectRoleGroup": "Role Group 1"
},
{
"WidgetID": 1,
"WidgetName": "Widget 1 ",
"ProjectRoleGroup": "Role Group 2"
},
{
"WidgetID": 2,
"WidgetName": "Widget 2",
"ProjectRoleGroup": "Role Group 3"
},
{
"WidgetID": 3,
"WidgetName": "Widget 3",
"ProjectRoleGroup": "Role Group 2"
},
{
"WidgetID": 4,
"WidgetName": "Widget 4",
"ProjectRoleGroup": "Role Group 3"
}
]
这是我想要使用Jquery的表:
请帮助。提前谢谢。
答案 0 :(得分:1)
使用下面的代码段。有3个步骤:
构建表格
<table id="tblRoles"></table>
<script>
var obj = [
{
"WidgetID": 1,
"WidgetName": "Widget 1 ",
"ProjectRoleGroup": "Role Group 1"
},
{
"WidgetID": 1,
"WidgetName": "Widget 1 ",
"ProjectRoleGroup": "Role Group 2"
},
{
"WidgetID": 2,
"WidgetName": "Widget 2",
"ProjectRoleGroup": "Role Group 3"
},
{
"WidgetID": 3,
"WidgetName": "Widget 3",
"ProjectRoleGroup": "Role Group 2"
},
{
"WidgetID": 4,
"WidgetName": "Widget 4",
"ProjectRoleGroup": "Role Group 3"
}
]
var getAllRoles = function () {
var roleGroups = [];
$.each(obj, function (i, v) {
if (roleGroups.indexOf(v.ProjectRoleGroup) == -1) {
roleGroups.push(v.ProjectRoleGroup);
}
});
return roleGroups;
}
var buildTableDataSource = function () {
var ret = [];
$.each(obj, function (i, v) {
var existed = $.grep(ret, function (e, i) {
return e.WidgetID == v.WidgetID;
});
if (existed.length) {
existed[0].Roles.push(v.ProjectRoleGroup);
} else {
ret.push({
WidgetID: v.WidgetID,
WidgetName: v.WidgetName,
Roles: [v.ProjectRoleGroup]
});
}
});
return ret;
}
var buildTable = function () {
var allRoles = getAllRoles();
var tableDataSource = buildTableDataSource();
var headerRow = $("<tr><td>Permission</td></tr>");
$.each(allRoles, function (i, v) {
headerRow.append('<td>' + v + '</td>');
});
$('#tblRoles').append(headerRow);
$.each(tableDataSource, function (i, v) {
var row = $('<tr><td>' + v.WidgetName + '</td></tr>');
$.each(allRoles, function (j, r) {
if (v.Roles.indexOf(r) > -1) {
row.append('<td><input type="checkbox" checked="checked" /></td>');
} else {
row.append('<td><input type="checkbox" /></td>');
}
$('#tblRoles').append(row);
});
});
}
$(document).ready(function () {
buildTable();
})