There seems to be quite a few posts about this around google and on stack overflow, however most of them aren't very descriptive and I'm just having a really hard time understanding. Solutions offered all talk about using an external library, which I cannot use.
I have a JavaScript object that looks similar (not exactly) to this:
var test = {[{ "question": "What are you doing?", "id": 1, "answers": [
{ "answer": "Eating some pizza", "correct": true },
{ "answer": "Working on my PC", "correct": false },
{ "answer": "Sitting in a chair", "correct": true }
]}]}
Obviously that is an array, because usually there will be multiple questions. Now what I'm doing is trying to make a page where I can edit the test, but I want to make sure that changes have been made to the test before sending it off to the backend for processing. There isn't any reason to send a request to the server if the test hasn't been modified. This means that if any character has been changed, a space has been added, an answer was changed from correct to incorrect, a question was added or removed, then this method would return true. Else it would return false.
The only third party library I'm allowed to use in AngularJS. I've tried the angular.equals(x,y) method and it didn't yield proper results.
One method that I've thought of using, which should have ideally of worked was the following:
function isEqual(obj1, obj2) {
return (JSON.stringify(obj1) == JSON.stringify(obj2));
}
However when a value (Such as a space " "
) is added, it will still return true, even though the objects are different. While printing the value, it seems that if the space is at the beginning end of a string it will be trimmed. (The same result as angular.equals
) However if a space is added between text, then the check returns false (as expected)
So what is the best way to check an object for equality with pinpoint accuracy?
Would appreciate if all answers are in raw javascript, and not using external libraries.