Is there a simple way to test equality of objects in CoffeeScript?
Or more correctly - test if the properties of two objects are identical.
With these objects:
obj1 =
name: "John Doe"
age: "3.14"
obj2 =
name: "John Doe"
age: "3.14"
This evaluates false, as expected:
obj1 == obj2
For now I'm using Underscore's isEqual
Is there a simple way to test equality of objects in CoffeeScript?
Or more correctly - test if the properties of two objects are identical.
With these objects:
obj1 =
name: "John Doe"
age: "3.14"
obj2 =
name: "John Doe"
age: "3.14"
This evaluates false, as expected:
obj1 == obj2
For now I'm using Underscore's isEqual
Share Improve this question edited Nov 22, 2012 at 0:53 mnorrish asked Nov 21, 2012 at 22:04 mnorrishmnorrish 4795 silver badges11 bronze badges 2-
3
What's wrong with
_.isEqual
? You need to perform some sort of deep equality. – Matt Ball Commented Nov 21, 2012 at 22:05 - There's nothing wrong with the Underscore method but I'd be interested in a short-hand language feature. – mnorrish Commented Nov 22, 2012 at 2:28
2 Answers
Reset to default 11Nope. CoffeeScript doesn't provide this as a language feature, so using a library like Underscore.js is your best option.
You can use the old standby:
JSON.stringify(obj1) == JSON.stringify(obj2)
Which will do the job - but may be too inefficient for some jobs.
You could also turn your arbitrary objects into a class and provide an equals method on the class.
class Person
constructor: (@name, @age) ->
equals: (other) -> @name == other.name && @age == other.age