Last active
February 7, 2018 02:02
-
-
Save mr21/8a59b6950a9032c7cba6231e400c72a9 to your computer and use it in GitHub Desktop.
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
"use strict"; | |
function diffObjects( a, b ) { | |
var ak, diff = {}; | |
Object.entries( b ).forEach( ( [ k, val ] ) => { | |
ak = a[ k ]; | |
if ( ak !== val ) { | |
if ( !val || typeof val !== "object" ) { | |
diff[ k ] = val; | |
} else if ( Array.isArray( val ) ) { | |
if ( !Array.isArray( ak ) || ak.toString() !== val.toString() ) { | |
diff[ k ] = Array.from( val ); | |
} | |
} else { | |
diff[ k ] = diffObjects( ak || {}, val ); | |
if ( !Object.keys( diff[ k ] ).length ) { | |
delete diff[ k ]; | |
} | |
} | |
} | |
} ); | |
return diff; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Be careful, this algorithm consider Arrays like an atomic value, like String, Number, etc.
You must prevent at the maximum the use of Array to store Objects if you want to use this algorithm.