我有一组用户的许可:
var permission = ["view_admin", "view_config", ...];
以及包含用户菜单的数组:
var items = [
{ title: 'a' },
{ title: 'b', rules: 'view_admin', sub: [
{ title: 'ba', rules: 'view_admin1' }
] },
{ title: 'c', sub: [
{ title: 'ca', rules: 'view_config', sub: [
{ title: 'caa', rules: 'view_config1' },
{ title: 'cba' }
] }
] },
{ title: 'd', rules: 'view_other'}
];
我需要:
所以在这种情况下我需要:
var items = [
{ title: 'a' },
{ title: 'b', rules: 'view_admin'},
{ title: 'c', sub: [
{ title: 'ca', rules: 'view_config', sub: [
{ title: 'cba' }
] }
] }
];
PS:我不知道可能有“sub”的数量......
这是我尝试过的代码但无法正常工作
var organizeMenu = function(items, permissions) {
for (var i = 0; i < items.length; i++) {
var title = items[i].title;
console.log(title);
if (items[i].rules && items[i].rules != '*') {
if (permissions.indexOf(items[i].rules) < 0) {
console.log("deleted");
delete items[i];
} else {
if (items[i].submenu) {
organizeMenu(items[i].submenu, permissions);
}
}
}
}
return items;
};
答案 0 :(得分:0)
我显然不想为你编写代码。不过我会写伪代码来帮助你。
定义函数,比如cleanItems(array)
var cleanItems = function(array){
//You need to iterate through all the items
for(until array.lenth){
condition1// compare if the rules don't match use permission.indexOf(ruleName)
recursively call clean items if the sub property exists
//arrayItem.sub = cleanItems(arrayItem.sub)
condition// delete if the object is empty
read more here about finding empty obect
}
return the processed array;
}
答案 1 :(得分:0)
基于对象给定的对象结构, 在这里我尝试过。
请检查。
var permission = ["view_admin", "view_config"];
var items = [
{ title: 'a' },
{ title: 'b', rules: 'view_admin', sub: [
{ title: 'ba', rules: 'view_admin1' }
] },
{ title: 'c', sub: [
{ title: 'ca', rules: 'view_config', sub: [
{ title: 'caa', rules: 'view_config1' },
{ title: 'cba' }
] }
] },
{ title: 'd', rules: 'view_other'}
];
function checkInnerObject(arrItems){
arrItems.forEach(function(objOne,key){
if(objOne.hasOwnProperty("rules") || objOne.hasOwnProperty("sub")){
if(permission.indexOf(objOne.rules)>=0){
checkInnerObject(objOne.sub);
if(objOne.sub.length==0){
delete objOne.sub;
}
}else if(objOne.hasOwnProperty("sub")){
checkInnerObject(objOne.sub);
} else{
arrItems.splice(key,1);
}
}
})
}
checkInnerObject(items);
console.log(items)