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

1
  • If you are sure about the order of the properties, you can JSON.stringify it and compare it. Commented May 10, 2017 at 8:56

2 Answers 2

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();
Sign up to request clarification or add additional context in comments.

2 Comments

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.
besides the ordering problem, this toLowerCase() is wrong, will make { x: 'FOo' } equal to { x: 'foo' }
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

1 Comment

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 ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.