var p1 = {
tags: ['one', 'two', 'three'],
name: 'Frank',
age: 24,
address: {
street: '111 E 222 W',
city: 'Provo',
state: 'Utah',
zip: '84604'
}
}
var p2 = {
name: 'Frank',
age: 24,
tags: ['one', 'two', 'three'],
address: {
street: '111 E 222 W',
city: 'Provo',
state: 'Utah',
zip: '84604'
}
}
var p3 = {
name: 'Amy',
age: 24,
tags: ['one', 'two', 'three'],
address: {
street: '111 E 222 W',
city: 'Provo',
state: 'Utah',
zip: '84604'
}
}
var p4 = {
name: 'Frank',
age: 24,
tags: ['one', 'two', 'three'],
address: {
street: '111 E 222 W',
city: 'Payson',
state: 'Utah',
zip: '84604'
}
}
var p5 = {
name: 'Frank',
age: 24,
tags: ['one', 'two'],
address: {
street: '111 E 222 W',
city: 'Provo',
state: 'Utah',
zip: '84604'
}
}
var equal = (function(){
function isObject(o){
return o !== null && typeof o === 'object';
}
return function(o1, o2){
if(!isObject(o1) || !isObject(o2)) return o1 === o2;
var key, allKeys = {};
for(key in o1)
if(o1.hasOwnProperty(key))
allKeys[key] = key;
for(key in o2)
if(o2.hasOwnProperty(key))
allKeys[key] = key;
for(key in allKeys){
if(!equal(o1[key], o2[key])) return false;
}
return true;
}
})();
var cases = [
{name: 'Compare with self', a: p1, b: p1, expected: true},
{name: 'Compare with identical', a: p1, b: p2, expected: true},
{name: 'Compare with different', a: p1, b: p3, expected: false},
{name: 'Compare with different (nested)', a: p1, b: p4, expected: false},
{name: 'Compare with different (nested array)', a: p1, b: p5, expected: false}
];
function runTests(tests){
var outEl = document.getElementById('out');
for(var i=0; i < tests.length; i++){
var actual = equal(tests[i].a, tests[i].b),
result = tests[i].expected == actual
? 'PASS'
: 'FAIL';
outEl.innerHTML +=
'<div class="test ' + result + '">' +
result + ' ' +
tests[i].name +
'</div>';
}
}
runTests(cases);
body{
font-family:monospace;
}
.test{
margin:5px;
padding:5px;
}
.PASS{
background:#EFE;
border:solid 1px #32E132;
}
.FAIL{
background:#FEE;
border:solid 1px #FF3232;
}
<div id=out></div>