0
"Roles":
{ 
    "0_A":["Developer"],
    "0_B":["Developer"],
    "0_C":["Developer","Tester","Player"],
    "0_D":["Tester"]
}

Is there a way to check if the value 'Player'/'Tester'/'Developer' exists anywhere in 'Roles' object? This is what I tried:

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

Is there a way to do this without for loop?

Thank you!

3 Answers 3

1

One alternative is to use Array.some() in conjunction with Array.includes() over the Object.Values() of the input object. An example fo how to do this is shown on the below snippet:

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

Sign up to request clarification or add additional context in comments.

Comments

1

How about using .find() and .includes as below:

let isPlayer = false;
if (response) {
  const roleNames = Object.values(response["Roles"]);
  const playerFound = roleNames.find(names => names.includes('Player'))
  isPlayer = !!playerFound;  
}

Comments

1

You could flatten the 2D array returned by Object.values() and use includes to check if the array contains the role name:

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.