Compare objects in JS

Gajender Tyagi - Sep 12 '21 - - Dev Community

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
Enter fullscreen mode Exit fullscreen mode

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); 
Enter fullscreen mode Exit fullscreen mode

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

. . . . . . . .