如何搜索此对象以查看用户是否拥有权限?

时间:2016-12-08 00:07:04

标签: javascript json object search recursion

鉴于我有:

var permissions = {
    'blog': {
    'article' : ['add_article', 'view_articles']
  },
  'gallery': {
    'images' : ['upload_image', 'view_other_user_images']
  }
}

var permissionsChecker = function(permissions) {
    this.permissions = permissions;
    this.hasPermissions = function (permissionsString) {
      // permissionsString is in this.permissions
      // return true
  }
}

如何在该对象中的数组中搜索以检查我是否拥有某项权限?我希望能够通过给出一个像这样的字符串进行搜索:

'blog.article.add_article' or 'gallery.images.view_other_user_images'

1 个答案:

答案 0 :(得分:1)

我可能没有正确理解,但我认为这是你正在寻找的:

var permissionsChecker = function(permissions) {
    this.permissions = permissions;
    this.hasPermissions = function (permissionsString) {
      var [section, subsection, permission] = permissionsString.split('.');
      if(this.permissions[section]){
        if(this.permissions[section][subsection]){
          return this.permissions[section][subsection].indexOf(permission) > -1;
        }
      }
      return false;
  }; 
}
var checker = new permissionsChecker(permissions);
checker.hasPermission('add_article');//true
checker.hasPermission('destroy_world');//false