Skip to content

Instantly share code, notes, and snippets.

@callerobertsson
Created April 28, 2013 22:18
Show Gist options
  • Save callerobertsson/5478643 to your computer and use it in GitHub Desktop.
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
// 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;
}
// 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