Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare two objects in Angular not using reference of object

how typescript comparing two objects?

originaltraits:{
artistic:25,
athletic:24,
goodLooks:70,
happiness:0,
health:81
}
newtraits:{
artistic:25,
athletic:24,
goodLooks:70,
happiness:0,
health:81
}

I have these two objects I want to compare these objects' fields not using object reference in Angular then how to compare?

Why does two equal Objects shows 'not equal" in Angular 2

like image 973
Karuna Dande Avatar asked May 10 '17 08:05

Karuna Dande


People also ask

How do you compare an object with another object?

Whereas the equals() method compares two objects. Objects are equal when they have the same state (usually comparing variables). Objects are identical when they share the class identity. For example, the expression obj1==obj2 tests the identity, not equality.

How do you compare object values?

Referential equality JavaScript provides 3 ways to compare values: The strict equality operator === The loose equality operator == Object.is() function.

How do I check if two objects are equal in AngularJS?

The equals() method in AngularJS basically checks if two objects or two values are equal or not. This method supports value types, regular expressions, arrays, and objects. It will return True if the reference objects passed inside the function are equal, else it will return False.


2 Answers

You can compare objects using JSON.stringify(), assuming you have the same order of object properties. i.e:

JSON.stringify(obj1).toLowerCase() === JSON.stringify(obj2).toLowerCase();
like image 131
Ricardo D. Ferrancullo III Avatar answered Oct 26 '22 13:10

Ricardo D. Ferrancullo III


If you need to do more comparisons like this one on your project, I highly recommend you using library like deep-equal:

https://www.npmjs.com/package/deep-equal

It has their types to be used with TypeScript:

https://www.npmjs.com/package/@types/deep-equal

like image 33
José Quinto Zamora Avatar answered Oct 26 '22 12:10

José Quinto Zamora