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
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.
Referential equality JavaScript provides 3 ways to compare values: The strict equality operator === The loose equality operator == Object.is() function.
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.
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();
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With