-3

All,

I'm currently writing validation for an "AND" RethinkDB query. A proper "AND" query containing "gt"(greater than) and "lt" (less than) would look like:

    "query": {
  "and": [
              { "gt": {"metadata.marvel_comics": 10} },
              { "lt": {"metadata.dc_comics": 50} }
            ]
        }

I'm trying to make sure that there are no extra objects included in the "gt" part of the query.

An incorrect query would be...

    "query": {
  "and": [
              { "gt": {"metadata.marvel_comics": 10} 
                 "eq": { "metadata.archie_comics": 10 }
              },
              { "lt": {"metadata.dc_comics": 50} }
            ]
        }

If I loop through the "and" array, how can I check if each object inside contains a nested any objects?

I don't want to have to test for each possibility of entries (e.g. "gt", "lt" "eq", "not", etc), I just want to know if a nested object exists. If so, the validation would fail.

edcincy
  • 321
  • 2
  • 3
  • 14

1 Answers1

0

Just check how many keys do the iterated object have:

var bQuery = {
  "query": {
    "and": [
      {
      "gt": {
        "metadata.marvel_comics": 10
      },
      "eq": {
        "metadata.archie_comics": 10
      }
    }, {
      "lt": {
        "metadata.dc_comics": 50
      }
    }]
  }
}

var gQuery = {
  "query": {
    "and": [
      {
      "gt": {
        "metadata.marvel_comics": 10
      }
    }, {
      "lt": {
        "metadata.dc_comics": 50
      }
    }]
  }
}

function validateQuery(obj){
  var and = obj.query.and;
  return and.every(function(comm){
    if(Object.keys(comm).length > 1){
      return false;
      } else {
        return true;
        }
    });
  }

console.log(validateQuery(bQuery), validateQuery(gQuery));
MinusFour
  • 13,913
  • 3
  • 30
  • 39
  • Excellent. Due to my current lack lack of JS knowledge, I wasn't even aware that the "every()" method existed. Thanks! – edcincy Oct 18 '15 at 18:30