1

I have an object like this but more complex:

var obj = 
{
  a: foo,
  b: bar,
  sub:{
    a: foz
    }
}

and then I have a conditionals based on the keys and values, for example:

{
  a: ^f,
  sub:{
     a: z$
  }
}

Is there a method for checking the conditionals are true for all of the objects properties. I'm also fine with chome-only-features or something like underscore. I can also re-structure the structure of my conditionals.

Himmators
  • 14,278
  • 36
  • 132
  • 223
  • No, there is no *built-in* method in browsers or underscore that does this. You will have to loop over the object and do this yourself. underscore can probably help you with the looping, but you will still have to do the comparison yourself. – gen_Eric Dec 26 '14 at 16:27
  • Your "conditionals" doesn't have a test for `b`. Would that mean it passes or fails? – gen_Eric Dec 26 '14 at 16:28
  • You can use something like [chai](http://chaijs.com/api/assert/) *deepEqual* if you are testing . – Mritunjay Dec 26 '14 at 16:28

1 Answers1

2

Probably you can use deepEqual() or modify it to your needs

var deepTest = function (x, y) {
  if ((typeof x == "object" && x != null) && (typeof y == "object" && y != null)) {
    if (Object.keys(x).length != Object.keys(y).length)
      return false;

    for (var prop in x) {
      if (y.hasOwnProperty(prop))
      {  
        if (! deepEqual(x[prop], y[prop]))
          return false;
      }
      else
        return false;
    }

    return true;
  }
  else if(x && (typeof y != "undefined")) return true; else return false;
}

document.write(deepEqual({a:{b:true}},{a:{c:1}}),'<br>');
document.write(deepEqual({a:{b:true}},{a:{b:1}}),'<br>');
document.write(deepEqual({a:{b:false}},{a:{c:1}}),'<br>');
document.write(deepEqual({a:{b:false}},{a:{b:1}}),'<br>');
document.write(deepEqual(true,true),'<br>');
document.write(deepEqual(true,false),'<br>');
document.write(deepEqual(false,false),'<br>');
document.write(deepEqual(false,false),'<br>');
document.write(deepEqual([true],[1]),'<br>');
document.write(deepEqual([true],[]),'<br>');
document.write(deepEqual([true],[]),'<br>');
document.write(deepEqual([true,true],[]),'<br>');
document.write(deepEqual([true,true],[1,2]),'<br>');
agershun
  • 4,077
  • 38
  • 41