Home > Mobile >  A cleaner and more cross-browser way to check a JSON value
A cleaner and more cross-browser way to check a JSON value

Time:07-14

I am working with an API, there is a value that is being stored as a variable(string type) that looks like this:

var majorValue = "some_major_name";

And then I want to check the above string value and compare it against a short list (group) of majors to load a related piece of HTML. I came up with this solution with includes but I am not sure if this is the cleanest/most efficient way:

if(majorValue.includes('Accounting') || majorValue.includes('Business_Administration') || majorValue.includes('BA_and_Accounting') || majorValue.includes('BA_and_Chemistry') || majorValue.includes('BA_and_Communication') || majorValue.includes('BA_and_Computer_Info_Systems') || majorValue.includes('BA_and_Economics') || majorValue.includes('BA_and_Sport_Management') || majorValue.includes('BA_and_Theatre') || majorValue.includes('Business_and_Visual_Arts')||majorValue.includes('Computer_Information_Systems')||majorValue.includes('Data_Analytics') || majorValue.includes('Economics') || majorValue.includes('Marketing') || majorValue.includes('Sustainable_Business')) {
  $('#internship').load(`./snippets/internship/Business.html`);
};

There should be a better way than writting a chunk of includes and || to check and load the HTML. Isn't it better to store the major values in an array and then check if majorValue is matching with one of the items in the array and if it does, then do something (load the HTML piece).

CodePudding user response:

const something = [
  'Accounting',
  'Business_Administration',
  'BA_and_Accounting',
  // ...
  'Marketing'
];

var majorValue = "Marketing";

if (something.includes(majorValue)) {
  console.log("found");
  //$('#internship').load(`./snippets/internship/Business.html`);
};

CodePudding user response:

Or the other way, use array for each of the candidates then find on it the item that is contained by your majorValue.

const something = [
  'Accounting',
  'Business_Administration',
  'BA_and_Accounting',
  // ...
  'Marketing'
];

var majorValue = "Marketing and stuff";


var x = something.find(function(item) {
  return majorValue.indexOf(item)>-1
})

console.log("found at", x)

  • Related