user989988
user989988

Reputation: 3736

Check if a value exists in an object array without for loop

"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!

Upvotes: 0

Views: 1063

Answers (3)

adiga
adiga

Reputation: 35202

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)

Upvotes: 1

Shidersz
Shidersz

Reputation: 17190

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

Upvotes: 1

Arup Rakshit
Arup Rakshit

Reputation: 118261

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

Upvotes: 1

Related Questions