Compare objects in JS

How can you compare to objects with same properties cause we know both the objects all though same values but sits at different memory location hence they will be not equal.

var user1 = {name : “nerd”, org: “dev”};
var user2 = {name : “nerd”, org: …


This content originally appeared on DEV Community and was authored by Gajender Tyagi

How can you compare to objects with same properties cause we know both the objects all though same values but sits at different memory location hence they will be not equal.

var user1 = {name : "nerd", org: "dev"};
var user2 = {name : "nerd", org: "dev"};
var eq = user1 == user2;
alert(eq); // gives false

Taken from Andrei course for Advance Javascript

Well a simple solution could be this

var user1 = {name : "nerd", org: "dev"};
var user2 = {name : "nerd", org: "dev"};
var eq = JSON.stringify(user1) == JSON.stringify(user2);
alert(eq); 

By converting the objects into sting the values can be compared but we have to be care full of the spaces and cases to be exact in both the objects.

A deep dive discussion for the same can be found on the stackoverflow page. The Page


This content originally appeared on DEV Community and was authored by Gajender Tyagi


Print Share Comment Cite Upload Translate Updates
APA

Gajender Tyagi | Sciencx (2021-09-12T08:38:31+00:00) Compare objects in JS. Retrieved from https://www.scien.cx/2021/09/12/compare-objects-in-js/

MLA
" » Compare objects in JS." Gajender Tyagi | Sciencx - Sunday September 12, 2021, https://www.scien.cx/2021/09/12/compare-objects-in-js/
HARVARD
Gajender Tyagi | Sciencx Sunday September 12, 2021 » Compare objects in JS., viewed ,<https://www.scien.cx/2021/09/12/compare-objects-in-js/>
VANCOUVER
Gajender Tyagi | Sciencx - » Compare objects in JS. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/09/12/compare-objects-in-js/
CHICAGO
" » Compare objects in JS." Gajender Tyagi | Sciencx - Accessed . https://www.scien.cx/2021/09/12/compare-objects-in-js/
IEEE
" » Compare objects in JS." Gajender Tyagi | Sciencx [Online]. Available: https://www.scien.cx/2021/09/12/compare-objects-in-js/. [Accessed: ]
rf:citation
» Compare objects in JS | Gajender Tyagi | Sciencx | https://www.scien.cx/2021/09/12/compare-objects-in-js/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.