Wing Choy Wing Choy - 3 months ago 6
Javascript Question

Is there any clear way to do a list of AND NOT conditions in javascript?

now I have a json object with following sample:

{
"a1": "xxx",
"a2": "xxx",
"a3": "xxx",
"b": "xxx",
"c": "xxx",
"d": "xxx",
"e": "xxx",
"f": "xxx"
}


which a1,a2,a3 do not always have the same key

(it may change key name as b1,b2,b3 or any other key name etc.)




Therefore, when I want to get these key's value, I will add the following condition inside a for-loop:

if (key!="b" && key!="c" && key!="d" && key!="e" && key!="f") {}


but I want to have a clear way to do this condition.

Is there any better solution for this?

Answer

For multiple conditions like this, I like to use an array and check if the value is in that array or not. Slightly more readable.

var key = 'a1';
var key2 = 'b';

if (['b', 'c', 'd', 'e', 'f'].indexOf(key) === -1) {
  console.log(key);
}

if (['b', 'c', 'd', 'e', 'f'].indexOf(key2) === -1) {
  console.log(key2);
}

var list = {
    "a1": "xxx",
    "a2": "xxx",
    "a3": "xxx",
    "b": "xxx",
    "c": "xxx",
    "d": "xxx",
    "e": "xxx",
    "f": "xxx"
};

var key;

for (key in list) {
  if (['b', 'c', 'd', 'e', 'f'].indexOf(key) === -1) {
    console.log('Key not in array', key);  
  } else {
    console.log('Key in array', key);  
  }
};