本质上,我试图遍历一系列角色,并将其相关权限与主列表数组进行比较,并在此循环内设置布尔值。因此,我想更改要遍历的原始数组,从主列表中添加不存在的值,并为原始值设置一个真正的键值对,为添加的值设置一个错误的键值对。我可以控制台注销循环中的所有数据,直到我注销最终结果(其中两个嵌套数组都包含循环中最后一次的布尔值)后,我编写的代码似乎按预期运行。我对地图的理解一定存在差距。我还觉得必须有一种不嵌套的简单方法(我正在尝试学习如何避免或重构)。
示例代码:
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
})
}
})
})
}
关于javascript - 嵌套在Foreach中的Map函数的行为不符合预期。为什么?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38022028/