本质上,我试图通过一个角色数组循环,并比较它的相关权限与主列表数组和设置布尔值在这个循环。所以我想改变我循环的原始数组,加入主列表中不存在的值,并为原始值设置一个真键值对,为添加的值设置一个假键值对。我可以控制台注销循环中的所有数据,我编写的代码似乎如我所期望的那样,直到我注销最终结果,其中两个嵌套数组都包含上次循环中的布尔值。我对地图的理解一定有差距。我还觉得,必须有一种更简单的方法来做到这一点,而不需要嵌套(我正在努力学习如何避免或重构)。
示例代码:
let roles = [];
let allPerms = [];
roles.push({
name: 'role 1',
label: 'role-label-1',
permissions: [
{
name: 'permission 1',
label: 'permission-1'
},
{
name: 'permission 2',
label: 'permission-2'
}]
},
{
name: 'role 2',
label: 'role-label-2',
permissions: [
{
name: 'permission 3',
label: 'permission-3'
},
{
name: 'permission 4',
label: 'permission-4'
}]
});
allPerms.push({
name: 'permission 1',
label: 'permission-1'
},
{
name: 'permission 2',
label: 'permission-2'
},
{
name: 'permission 3',
label: 'permission-3'
},
{
name: 'permission 4',
label: 'permission-4'
});
console.log(roles);
console.log(allPerms);
function setRoles() {
roles.forEach(function (val, key, array) {
let selected = _.difference(array[key].permissions, allPerms);
let mappedPerms = allPerms.map( function(v, k) {
let name = _.find(selected, function(i) {
return i.name == v.name;
});
if (typeof name != "undefined" && name.name == v.name) {
v.selected = true;
} else if (typeof name == "undefined"){
v.selected = false;
}
return v;
});
console.log('ROLE '+key);
console.log(mappedPerms[0].selected);
console.log(mappedPerms[0].name);
console.log(mappedPerms[1].selected);
console.log(mappedPerms[1].name);
console.log(mappedPerms[2].selected);
console.log(mappedPerms[2].name);
console.log(mappedPerms[3].selected);
console.log(mappedPerms[3].name);
array[key].permissions = mappedPerms
});
return roles;
}
let testRoles = setRoles();
console.log(testRoles);
这是一个jSFiddle工作的例子:https://jsfiddle.net/patrickisgreat/fu3hza1w/1/
预期输出:[
{
"name": "role 1",
"label": "role-label-1",
"permissions": [
{
"name": "permission 1",
"label": "permission-1",
"selected": true
},
{
"name": "permission 2",
"label": "permission-2",
"selected": true
},
{
"name": "permission 3",
"label": "permission-3",
"selected": false
},
{
"name": "permission 4",
"label": "permission-4",
"selected": false
}
]
},
{
"name": "role 2",
"label": "role-label-2",
"permissions": [
{
"name": "permission 1",
"label": "permission-1",
"selected": false
},
{
"name": "permission 2",
"label": "permission-2",
"selected": false
},
{
"name": "permission 3",
"label": "permission-3",
"selected": true
},
{
"name": "permission 4",
"label": "permission-4",
"selected": true
}
]
}
]
Array.prototype.some
在这里可能对您有用。forEach
角色映射到allPerms
,重构角色权限。role.permissions.some
可用于检查角色是否预先存在给定的权限。
function setRoles() {
roles.forEach(function (role) {
role.permissions = allPerms.map(function (perm) {
return {
name: perm.name,
label: perm.label,
selected: role.permissions.some(function (rolePerm) {
return rolePerm.name === perm.name
})
}
})
})
}