Skip to content

Instantly share code, notes, and snippets.

@Kosmin
Last active August 29, 2015 14:23
Show Gist options
  • Save Kosmin/86fe519f02170836736a to your computer and use it in GitHub Desktop.
Save Kosmin/86fe519f02170836736a to your computer and use it in GitHub Desktop.
Simple Javascript deep object comparison (shows diff)
# Shows in an understandable format what the diff is between two hashes.
# I've only really used this for debugging purposes
deepCompare = (source, destination, stack = []) ->
# This relies on angular, but this line can be replaced with return if source == destination
return if angular.equals(source, destination)
# Object and not array
if typeof source == 'object' && source.constructor != Array
# invalid destination or different types
if !destination? || (typeof destination != 'object' || destination.constructor == Array)
console.log "#{stack} <=> source: #{source}, destination: #{destination}"
return
# For the case when destination has keys not in the source, since
# the loop below won't catch catch this
if !angular.equals(Object.keys(source), Object.keys(destination))
console.log "#{stack} <=> source: ", source, "destination:", destination
console.log "(different keys)"
console.log "source:", Object.keys(source)
console.log "destination:", Object.keys(destination)
return
# We know now we have 2 objects, so compare their keys
for key, elem of source
newStack = JSON.parse(JSON.stringify(stack))
newStack.push("[#{key}]")
deepCompare(source[key], destination[key], newStack)
# Array ?
else if source?.constructor == Array
if destination?.constructor != Array
console.log "#{stack} <=> source: #{source}, destination: #{destination}"
return
for elem, index in source
# just a very raw way of duplicating the object
newStack = JSON.parse(JSON.stringify(stack))
newStack.push("[#{index}]")
deepCompare(source[index], destination[index], newStack)
else
console.log "#{stack} <=> source: #{source}, destination: #{destination}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment