迭代数组并删除

时间:2015-07-06 07:59:51

标签: javascript

我有一组用户的许可:

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'}
];

我需要:

  • 如果数组的对象不包含关键“规则”,则维护项目
  • 如果规则未获得用户的许可,请删除该对象
  • 如果规则是sub和length相等0删除整个sub, 因此删除子
  • 中的项目

所以在这种情况下我需要:

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;
};

2 个答案:

答案 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)