"Roles":
{
"0_A":["Developer"],
"0_B":["Developer"],
"0_C":["Developer","Tester","Player"],
"0_D":["Tester"]
}
有没有办法检查'Roles'对象中是否存在值'Player'/'Tester'/'Developer'?这是我尝试过的:
let isPlayer= false;
if (response) {
const k = Object.keys(response["Roles"]);
for (let index = 0; index < k.length; index++) {
if (response["Roles"][k[index]].indexOf("Player") > -1) {
isPlayer= true;
break;
}
}
}
有没有没有for循环的方法?
谢谢!
答案 0 :(得分:1)
答案 1 :(得分:1)
一种替代方法是在输入对象的Array.some()上将Array.includes()与Object.Values()结合使用。以下代码段显示了如何执行此操作的示例:
const response = {};
response["Roles"] = {
"0_A":["Developer"],
"0_B":["Developer"],
"0_C":["Developer","Tester","Player"],
"0_D":["Tester"]
};
const checkForType = (resp, type) =>
{
let typeExists = false;
if (resp)
{
let roles = resp["Roles"] || {};
typeExists = Object.values(roles).some(arr => arr.includes(type));
}
return typeExists;
}
console.log(checkForType(response, "Player"));
console.log(checkForType(response, "Developer"));
console.log(checkForType(response, "Team Leader"));
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}
答案 2 :(得分:1)
您可以flatten Object.values()
返回的2D数组,然后使用includes
检查该数组是否包含角色名称:
const response = {
"Roles": {
"0_A": ["Developer"],
"0_B": ["Developer"],
"0_C": ["Developer", "Tester", "Player"],
"0_D": ["Tester"]
}
}
let isPlayer = Object.values(response.Roles)
.flat()
.includes("Player")
console.log(isPlayer)