Created
November 25, 2016 10:52
-
-
Save Zabanaa/8a502dc336fb307378ce9b79ae114f17 to your computer and use it in GitHub Desktop.
Object comparison in Javascript
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
// Based on: http://stackoverflow.com/questions/14368596/how-can-i-check-that-two-objects-have-the-same-set-of-property-names | |
Object.prototype.isIdenticalTo = function(targetObject) { | |
// check that targetObject is an object | |
// if no argument is passed and it's not an object | |
// throw an error | |
if (!targetObject || typeof(targetObject) !== "object") { | |
throw new Error("Argument of type Object must be passed") | |
} | |
let objKeys = Object.keys(this).sort() | |
let targetKeys = Object.keys(targetObject).sort() | |
return JSON.stringify(objKeys) === JSON.stringify(targetKeys) | |
} | |
let obj = {name: "karim benz", club: "Real Madrid CF"} | |
let obj2 = { club: "Real Madrid CF", name: "karim benz"} | |
console.log(obj.isIdenticalTo(obj2)) // Should return true | |
obj2['shirtNo'] = 9 | |
console.log(obj.isIdenticalTo(obj2)) // Should return false | |
console.log(obj.isIdenticalTo()) // Should return an error | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment