Recently, I ran into a problem where I had to search for certain values contained within an array of objects. If anyone of these excluded values is found, I was then supposed to carry out some action. Here is how to go about it:
Here is our sample data where we want to check if a certain user role/roles exist in order to carry out an action based on if this role exists or not:
const data = {
users: [
{
id: 1,
name: "John Smith",
role: 'QA'
},
{
id: 2,
name: "Sally Roberts",
role: 'Engineer'
},
{
id: 3,
name: "Peter Johnson",
role: "Product Manager"
},
{
id: 4,
name: "Jason Sen",
role: "Project Manager"
},
{
id: 5,
name: "Benjamin Askin",
role: "System Administrator"
},
{
id: 6,
name: "Patricia Thompson",
role: "IT Manager",
},
]
};
We then create an array with the roles that we want to look for:
//Strings are case sensitive. They must be an exact match
const rolesToLookFor = ["Project Manager", "System Administrator", "IT Manager"];
We then create a new array with all the roles contained in the data set:
const allRoles = data.users.map((x) => x.role);
We then use the JavaScript functions some
and includes
in order to check whether these roles that are in the data set exist or not. some
takes a callback function and checks whether at minimum there is a single element in an array that matches what we are looking for, while includes
checks every element in an array to see if there is a match. We will use the rolesToLookFor
array that we created along with the allRoles
array:
const result = rolesToLookFor.some((role) => {
return allRoles.includes(role);
});
The result that we will receive will be a boolean. Either true
if a role is found or false
if it is not.