Skip to content

Instantly share code, notes, and snippets.

@Zabanaa
Created November 25, 2016 10:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Zabanaa/8a502dc336fb307378ce9b79ae114f17 to your computer and use it in GitHub Desktop.
Save Zabanaa/8a502dc336fb307378ce9b79ae114f17 to your computer and use it in GitHub Desktop.
Object comparison in Javascript
// 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