Skip to content

Instantly share code, notes, and snippets.

@edwardsmarkf
Last active January 30, 2017 17:34
Show Gist options
  • Save edwardsmarkf/25ffca81031ebb7deb8a7bb05777f50d to your computer and use it in GitHub Desktop.
Save edwardsmarkf/25ffca81031ebb7deb8a7bb05777f50d to your computer and use it in GitHub Desktop.
demonstration of deep-object-diff by matt phillipp
'use strict'
const diff = require('deep-object-diff').detailedDiff ; // thank you matt phillip.
const util = require('util') ;
var rhs = {}
var lhs =
[ { sequelizeName : 'Lori Edwards'
, sequelizeAddr : '948 South 3rd street'
, id : 123
}
, { sequelizeName : 'Mark Edwards'
, sequelizeAddr : '123 Swallow'
, id : 234
}
, { sequelizeName : 'Marjorie Edwards'
, sequelizeAddr : '7366 East Ironwood Court'
, id : 987
}
]
;
rhs = JSON.parse(JSON.stringify(lhs));
diffMe(lhs, rhs) ;
rhs = JSON.parse(JSON.stringify(lhs));
rhs[0]['sequelizeAddr'] = '938 SOUTH THIRD STREET' ;
diffMe(lhs, rhs) ;
rhs = JSON.parse(JSON.stringify(lhs));
rhs.push( { sequelizeName: 'Orville Marsh', sequelizeAddr: '190 East Elm' } );
diffMe(lhs, rhs) ;
rhs = JSON.parse(JSON.stringify(lhs));
delete rhs[2] ;
diffMe(lhs, rhs) ;
function diffMe(lhs, rhs) {
var diffResult = diff(lhs, rhs) ;
for ( var newKey in diffResult ) {
switch ( newKey ) {
case 'updated' :
if ( typeof diffResult[newKey][0] === 'object' ) {
// {"1":{"TWO_2":"two two edited!"}}
var objRowNbr = Object.keys(diffResult[newKey]);
console.log( 'UPDATE WHERE ID = ' + rhs[objRowNbr]['id'] + ' -- ' + JSON.stringify(diffResult[newKey][objRowNbr]) );
}
break;
case 'added' :
if ( Object.keys(diffResult[newKey]).length ) {
// example: {"2":{"THREE_1":"three one","THREE_2":"three two"}}
console.log('INSERT INTO XX VALUES ' + JSON.stringify(diffResult[newKey][Object.keys(diffResult[newKey])]));
}
break;
case 'deleted' :
if ( ( diffResult[newKey] )
&& ( Object.keys(diffResult[newKey]).length )
)
{ // example - {"1":{}}
console.log('DELETE FROM XXXX WHERE 1 AND ID = ' + Object.keys(diffResult[newKey]) );
}
break;
default :
console.log('error with: ' + newKey);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment