Did you know? DZone has great portals for Python, Cloud, NoSQL, and HTML5!

John is the manager and founding member of the official Adobe ColdFusion User Group for Devon. An Adobe Certified Expert in Advanced ColdFusion, John regularly blogs about ColdFusion and contributes to several FOSS projects. His hobbies include writing in the third person. John has posted 20 posts at DZone. You can read more from them at their website. View Full User Profile

Comparing two Objects

06.20.2011
Email
Views: 5003
  • submit to reddit

I recently wanted to compare two objects to see if they were the same. After looking through the cfml ref I couldn't find anything, but I did find that you can use ArrayFind to do it.

Here's a quick test I wrote:

Foo.cfc

component 
{ 
  this.uuid = CreateUUID(); 
}

test.cfm

<cfset foo = new foo()>
<cfset bar = new foo()>
<cfoutput>

is foo equal to foo? #ArrayFind( [foo], foo ) gt 0#<br />
is foo equal to bar? #ArrayFind( [foo], bar ) gt 0#<br />
</cfoutput>

The output when I run this script is:

is foo equal to foo? YES

is foo equal to bar? NO

It also works with persistent entities, this is a test I wrote using the cfcodeexplorer datasource:

<cfset NewArtist = EntityNew( "Artist" )>
<cfset Artist = EntityLoadByPK( "Artist", 1 )>
<cfset Artist2 = EntityLoadByPK( "Artist", 1 )>

<cfset foo = new foo()>

<cfoutput>
is Artist equal to Artist? #ArrayFind( [Artist], Artist ) gt 0#<br />
is NewArtist equal to Artist? #ArrayFind( [NewArtist], Artist ) gt 0#<br />
is Artist equal to Artist2? #ArrayFind( [Artist], Artist2 ) gt 0#<br />
is foo equal to Artist? #ArrayFind( [foo], Artist ) gt 0#
</cfoutput>

The output when I run this script is:

is Artist equal to Artist? YES
is NewArtist equal to Artist? NO
is Artist equal to Artist2? YES
is foo equal to Artist? NO

References
Tags:
Published at DZone with permission of its author, John Whish. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Comments

Sirikant Noori replied on Sun, 2012/01/15 - 1:08pm

be careful. ArrayFind will only compare the property with fieldtype="id" when component persistent=true.

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.