Compare objects

by ellhn

JavaScript

Object.prototype.isEqual = function (obj) {
  if (this === null || this === undefined || obj === null || obj === undefined) {
    return this === obj; 
  }
	//Loop through properties in object 1
	for (let p in this) {
		//Check if property exists on both objects
		if (this.hasOwnProperty(p) !== obj.hasOwnProperty(p)) return false;
 
		switch (typeof (this[p])) {
			//Deep compare objects
			case 'object':
				if (!this[p].isEqual(obj[p])) return false;
				break;
			//Compare values
			default:
				if (this[p] != obj[p]) return false;
		}
	}
 
	//Check object 2 for any extra properties
	for (let p in obj) {
    if (typeof (this[p]) === 'undefined') return false;
	}
	return true;
};

var obj1 = {
    name: "John",
    age: 10,
    info: {
        address: 'some place',
        tel: '0123456789',
        hobbies: ['1', '2']
    }
}

var obj2 = {
    name: "John",
    age: 10,
    info: {
        address: 'some place',
        tel: '0123456789',
        hobbies: ['1', '2']
    }
}

var smallObj = {
    name: "John",
    age: 10
}


var obj3 = obj2;
var obj4 = obj1;

console.log(smallObj.isEqual(obj1)); //return false;
console.log(smallObj.isEqual({name:'John'})); //return false;
console.log(obj1.isEqual(undefined)); //return false;
console.log(obj2.isEqual(obj1)); //returns true;
console.log(obj3.isEqual(obj1)); //returns true;
console.log(obj4.isEqual(obj1)); //returns true;