user582734
user582734

Reputation: 45

Comparing the values of two different objects

I have two objects.

"Initial": {"LF_Min": --,
          "LF_Max": --,
          "RF_Min": --,
          "RF_Max": --};

"Result":{"LF_Status":--,
          "RF_Status":--};

I have to check if the value of Result.LF_Status is in the range of Initial.LF_Min and Initial.LF_Max or not.

How can I check for this condition in JavaScript?

Upvotes: 0

Views: 73

Answers (3)

instanceofnull
instanceofnull

Reputation: 1071

Assuming the properties in your objects are of type Number:

function validate(initial, result) {
  return
    result.LF_Status >= initial.LF_Min &&
    result.LF_Status <= initial.LF_Max;
}

When I'm extensively checking for range constraints, I find it useful to extend the Number prototype like so:

Number.prototype.isInRange = function(min, max) {
  return this >= min && this <= max;
}

With this extension defined, you can achieve your object validation in a more concise way:

if(Result.LF_Status.isInRange(Initial.LF_Min, Initial.LF_Max)) {
  // Your code here
}

Hope this helps!

Upvotes: 2

doldt
doldt

Reputation: 4506

First of all, there's no such thing as a "JSON object" - if you have the JSON representation of two objects, they are basically string literals that can be parsed into a Javascript object. Once you parse them into javascript objects (using object = JSON.parse(string)), you can manipulate them in standard ways, ie. use 2 comparisons to assert that the value of result is in the desired range.

Upvotes: -1

Naeem Shaikh
Naeem Shaikh

Reputation: 15715

see this : http://jsfiddle.net/dwboy657/

Initial={"LF_Min": "10", "LF_Max": "20", "RF_Min": "30", "RF_Max": "50"};
Result={"LF_Status":"21", "RF_Status":"4"};

function checkRange(compareObj,resultObj){
    if(resultObj.LF_Status>=compareObj.LF_Min && resultObj.LF_Status<=compareObj.LF_Max)
    {
       return true;
    }else{
         return false;
    }

}

alert('Result LF is within range: '+checkRange(Initial,Result));

Upvotes: 1

Related Questions