-2

I need to compare two objects. But it fails.

Code:

export class SourceValues {
  ...
  static INDICATOR: ISourceValue = { text: 'Indicator', value: 'Indicator' };
  ...
}

somewhere else

let a = { text: 'Indicator', value: 'Indicator' } as ISourceValue;
...
if(a === SourceValues.INDICATOR){ // I don't want any change here
//do something
}

When I run this, both a and SourceValues.INDICATOR holds the same value / object. but the comparison fails. Let me know your thoughts. Thanks.

Ranjith Varatharajan
  • 1,596
  • 1
  • 33
  • 76

2 Answers2

0

You can't use === to compare objects in javascript. In javascript === compare memory location as its an object, as both objects have different memory locations it will always be false.

Refer to this answer to compare two objects properly.

B45i
  • 2,368
  • 2
  • 23
  • 33
0

Unline primary types, objects are compared by their references and will not result as equal. Check the link for further reading: http://adripofjavascript.com/blog/drips/object-equality-in-javascript.html

Sunny
  • 133
  • 1
  • 7