How to check an input matches property values in an array of objects in JavaScript?

Background

Based on my previous post and playing a little more with some useful JavaScript functions, I came across a very inefficient way of determining whether a given user was member of a role based on its provisioned list of roles. Here is how that list looks like:

var userRoles = [
  {roleCode: "GlobalAdmin", roleDescription: "Global Administrator"},
  {roleCode: "TechnicalAdmin", roleDescription: "Technical Administrator"},
  {roleCode: "GlobalUser", roleDescription: "Global User"}
]

The sub-optimal code worked out the membership by iterating trough the array by using loops. Please, don't do this when already existing JavaScript functions can do the same for you.

Solution

Let's say we need to check a given user belongs to the GlobalAdmin role. How to do it?

First of all, let me reminder you the use of filter() JavaScript function. It creates a new array with all elements based on the result (true/false) returned by the provided function.

So, we just need to add the following code:

var userRoles = [
  {roleCode: "GlobalAdmin", roleDescription: "Global Administrator"},
  {roleCode: "TechnicalAdmin", roleDescription: "Technical Administrator"},
  {roleCode: "GlobalUser", roleDescription: "Global User"}
]
var isGlobalAdminUser = userRoles.filter(function (e) { return e.roleCode == "GlobalAdmin" }).length > 0;
console.log("Global Admin User: " + isGlobalAdminUser )

By using the filter() JavaScript function, we get the list of elements that pass the validation provided by the custom provided function. This way, we just need to verify the new output array contains at least one element.

You can also use other JavaScript functions to do the same in a different way. For instance, you may get the same result by employing the find() method. It does not return a new array of elements based on a condition but the first element that matches your rules. It is perfectly valid for us in this scenario. Here is the code:

var userRoles = [
  {roleCode: "GlobalAdmin", roleDescription: "Global Administrator"},
  {roleCode: "TechnicalAdmin", roleDescription: "Technical Administrator"},
  {roleCode: "GlobalUser", roleDescription: "Global User"}
]
var objResult = userRoles.find(function (e) { return e.roleCode == "GlobalAdmin" });
var isGlobalAdminUser = objResult != null;
console.log("Global Admin User: " + isGlobalAdminUser )

 I hope this helps!

 

Add comment