简体   繁体   English

Javascript-如何遍历对象中键的值?

[英]Javascript - How do I iterate over values of keys in an object?

var roles = {
    Guest: ["CAN_REGISTER"],
    Player: ["CAN_LOGIN", "CAN_CHAT"],
    Admin: ["CAN_KICK", "CAN_LOGIN", "CAN_CHAT"]
};

that is my object and I am trying to check if the user has specific perms 那是我的目标,我正在尝试检查用户是否具有特定的权限

get_perms: function(player, perm) {
    let arrayLength = accounts.length;
    let name = player.name;

    if (arrayLength == 0 && (perm == "CAN_CHAT" || perm == "CAN_LOGIN" || perm == "CAN_KICK")){
        return false;
    }

    for (var i = 0; i < arrayLength; i++)
    {
        if (accounts[i][0] == name)
        {
            for (var key in roles)
            {
                if (roles.hasOwnProperty(key))
                {
                    if (accounts[i][2] == key){

                        if (roles[key] == perm){
                            for (var x = 0; x < roles[key].length; x++){
                                if (roles[key][x] == perm){
                                    return true;
                                }
                            }
                        }
                    }
                }
            }
        }
        else{
            return false;
        }
    }
}

account[i][2] is the role of the player which matches the name, I am trying to check if that role has perm which is sent to the function, for example "CHAT_PERMS" account[i][2]是与名称匹配的玩家角色,我正在尝试检查该角色是否具有发送至该功能的perm ,例如"CHAT_PERMS"

const roles = {
    Guest: ["CAN_REGISTER"],
    Player: ["CAN_LOGIN", "CAN_CHAT"],
    Admin: ["CAN_KICK", "CAN_LOGIN", "CAN_CHAT"]
};

const arr = Object.keys(roles).reduce((acc, cur) => [...acc, ...roles[cur]], []);
console.log(arr);
const rightSet = new Set(arr);
console.log(rightSet.has("CAN_CHAT"))

This is my solution using ES6: 这是我使用ES6的解决方案:

  1. Use reduce with array spread syntax to create a flat array, which give you [ "CAN_REGISTER", "CAN_LOGIN", "CAN_CHAT", "CAN_KICK", "CAN_LOGIN", "CAN_CHAT" ] 使用带有数组扩展的reduce语法来创建一个平面数组,该数组将为您提供[ "CAN_REGISTER", "CAN_LOGIN", "CAN_CHAT", "CAN_KICK", "CAN_LOGIN", "CAN_CHAT" ]
  2. Save this array in a set 将此数组保存为一组
  3. Use has() function to check if the right in the Set 使用has()函数检查Set是否正确

Use a for-loop and the function includes to check the role and permission. 使用for-loop ,该功能includes检查角色和权限。

 var roles = { Guest: ["CAN_REGISTER"], Player: ["CAN_LOGIN", "CAN_CHAT"], Admin: ["CAN_KICK", "CAN_LOGIN", "CAN_CHAT"] }; var playerRoles = ['Admin', 'Guest']; var perm = 'CAN_LOGIN'; var found = false; for (var role of playerRoles) { if ((found = roles[role].includes(perm))) { console.log("Permission '"+perm+"' found in Role '" + role + "'"); break; } } if (!found) { console.log("Permission '"+perm+"' didn't found"); } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM