6

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

Community
  • 1
  • 1
Karuna Dande
  • 93
  • 1
  • 1
  • 10

2 Answers2

20

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();
  • 5
    The problem with this approach is that, object `{Foo=1, Bar =123}` is not equal to object `{Bar =123, Foo=1}`, Some ordering would help. – Rzassar Jun 02 '19 at 15:59
  • 1
    besides the ordering problem, this `toLowerCase()` is wrong, will make `{ x: 'FOo' }` equal to `{ x: 'foo' }` – Bogdan D Jul 16 '20 at 12:47
2

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

José Quinto Zamora
  • 2,070
  • 12
  • 15
  • I get this error if i use deep-equal. error TS2497: Module '"/angularCodeFolder/node_modules/@types/deep-equal/index"' resolves to a non-module entity and cannot be imported using this construct. What could be the issue ? – Sagar Agrawal Apr 16 '21 at 14:24