How do I determine if two jQuery objects are equal? I would like to be able to search an array for a particular jQuery object.
$.inArray(jqobj, my_array);//-
If you want to check contents are equal or not then just use JSON.stringify(obj)
Eg - var a ={key:val};
var b ={key:val};
JSON.stringify(a) == JSON.stringify(b) -----> If contents are same you gets true.
Use Underscore.js isEqual method http://underscorejs.org/#isEqual
The $.fn.equals(...)
solution is probably the cleanest and most elegant one.
I have tried something quick and dirty like this:
JSON.stringify(a) == JSON.stringify(b)
It is probably expensive, but the comfortable thing is that it is implicitly recursive, while the elegant solution is not.
Just my 2 cents.
If you still don't know, you can get back the original object by:
alert($("#deviceTypeRoot")[0] == $("#deviceTypeRoot")[0]); //True
alert($("#deviceTypeRoot")[0] === $("#deviceTypeRoot")[0]);//True
because $("#deviceTypeRoot")
also returns an array of objects which the selector has selected.
It is, generally speaking, a bad idea to compare $(foo) with $(foo) as that is functionally equivalent to the following comparison:
<html>
<head>
<script language='javascript'>
function foo(bar) {
return ({ "object": bar });
}
$ = foo;
if ( $("a") == $("a") ) {
alert ("JS engine screw-up");
}
else {
alert ("Expected result");
}
</script>
</head>
</html>
Of course you would never expect "JS engine screw-up". I use "$" just to make it clear what jQuery is doing.
Whenever you call $("#foo") you are actually doing a jQuery("#foo") which returns a new object. So comparing them and expecting same object is not correct.
However what you CAN do may be is something like:
<html>
<head>
<script language='javascript'>
function foo(bar) {
return ({ "object": bar });
}
$ = foo;
if ( $("a").object == $("a").object ) {
alert ("Yep! Now it works");
}
else {
alert ("This should not happen");
}
</script>
</head>
</html>
So really you should perhaps compare the ID elements of the jQuery objects in your real program so something like
...
$(someIdSelector).attr("id") == $(someOtherIdSelector).attr("id")
is more appropriate.
First order your object based on key using this function
function sortObject(o) {
return Object.keys(o).sort().reduce((r, k) => (r[k] = o[k], r), {});
}
Then, compare the stringified version of your object, using this funtion
function isEqualObject(a,b){
return JSON.stringify(sortObject(a)) == JSON.stringify(sortObject(b));
}
Here is an example
Assuming objects keys are ordered differently and are of the same values
var obj1 = {"hello":"hi","world":"earth"}
var obj2 = {"world":"earth","hello":"hi"}
isEqualObject(obj1,obj2);//returns true