Created
April 28, 2013 22:18
-
-
Save callerobertsson/5478643 to your computer and use it in GitHub Desktop.
Javascript: Object comparision with ignored fields. Original source can be found at http://www.sencha.com/forum/showthread.php?59240-Compare-javascript-objects but without ignored fields. #snippet
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// The javascript compare objects function | |
function compareObjects(o1, o2, ignoreFields){ | |
ignoreFields = ignoreFields || []; | |
//console.log('Ignore: ' + JSON.stringify(ignoreFields)); | |
for(var p in o1) { | |
if (ignoreFields.indexOf(p) < 0) { | |
if(o1[p] !== o2[p]){ | |
return false; | |
} | |
} | |
// else { | |
// console.log('Ignoring ' + p); | |
// } | |
} | |
for(var p in o2){ | |
if (ignoreFields.indexOf(p) < 0) { | |
if(o1[p] !== o2[p]){ | |
return false; | |
} | |
} | |
// else { | |
// console.log('Ignoring ' + p); | |
// } | |
} | |
return true; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// NodeUnit test case | |
this.suitApplications = { | |
'Test compareObjects on very equal objects': function (test) { | |
var o1 = {apa: 'Apa', bepa: 'Bepa'}; | |
var o2 = {bepa: 'Bepa', apa: 'Apa'}; | |
test.ok(compareObjects(o1, o2)); | |
test.done(); | |
} | |
,'Test compareObjects on unorder but equal objects': function (test) { | |
var o1 = {apa: 'Apa', bepa: 'Bepa'}; | |
var o2 = {bepa: 'Bepa', apa: 'Apa'}; | |
test.ok(compareObjects(o1, o2)); | |
test.done(); | |
} | |
,'Test compareObjects on inequal objects': function (test) { | |
var o1 = {apa: 'Apa', bepa: 'Bepa'}; | |
var o2 = {cepa: 'Cepa', depa: 'Depa'}; | |
test.ok(!compareObjects(o1, o2)); | |
test.done(); | |
} | |
,'Test compareObjects on inequal objects with unneeded ignore fileds': function (test) { | |
var o1 = {apa: 'Apa', bepa: 'Bepa'}; | |
var o2 = {apa: 'Apa', cepa: 'Ignore me', bepa: 'Bepa'}; | |
test.ok(!compareObjects(o1, o2, ['xepa'])); | |
test.done(); | |
} | |
,'Test compareObjects on inequal objects with ignore fileds': function (test) { | |
var o1 = {apa: 'Apa', bepa: 'Bepa'}; | |
var o2 = {apa: 'Apa', cepa: 'Ignore me', bepa: 'Bepa'}; | |
test.ok(compareObjects(o1, o2, ['cepa'])); | |
test.done(); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment