Created
December 5, 2013 21:44
-
-
Save xtbl/7814485 to your computer and use it in GitHub Desktop.
Find differences in JS objects
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
var deepDiffMapper = function() { | |
return { | |
VALUE_CREATED: 'created', | |
VALUE_UPDATED: 'updated', | |
VALUE_DELETED: 'deleted', | |
VALUE_UNCHANGED: 'unchanged', | |
map: function(obj1, obj2) { | |
if (this.isFunction(obj1) || this.isFunction(obj2)) { | |
throw 'Invalid argument. Function given, object expected.'; | |
} | |
if (this.isValue(obj1) || this.isValue(obj2)) { | |
//return {type: this.compareValues(obj1, obj2), data: obj1 || obj2}; | |
return this.compareValues(obj1, obj2); | |
} | |
var diff = {}; | |
for (var key in obj1) { | |
if (this.isFunction(obj1[key])) { | |
continue; | |
} | |
var value2 = undefined; | |
if ('undefined' != typeof(obj2[key])) { | |
value2 = obj2[key]; | |
} | |
diff[key] = this.map(obj1[key], value2); | |
} | |
for (var key in obj2) { | |
if (this.isFunction(obj2[key]) || ('undefined' != typeof(diff[key]))) { | |
continue; | |
} | |
diff[key] = this.map(undefined, obj2[key]); | |
} | |
return diff; | |
}, | |
compareValues: function(value1, value2) { | |
if (value1 === value2) { | |
return this.VALUE_UNCHANGED; | |
} | |
if ('undefined' == typeof(value1)) { | |
return this.VALUE_CREATED; | |
} | |
if ('undefined' == typeof(value2)) { | |
return this.VALUE_DELETED; | |
} | |
return this.VALUE_UPDATED; | |
}, | |
// use lodash functions | |
isFunction: function(obj) { | |
return toString.apply(obj) === '[object Function]'; | |
}, | |
isArray: function(obj) { | |
return toString.apply(obj) === '[object Array]'; | |
}, | |
isObject: function(obj) { | |
return toString.apply(obj) === '[object Object]'; | |
}, | |
isValue: function(obj) { | |
return !this.isObject(obj) && !this.isArray(obj); | |
} | |
} | |
}(); | |
var result = deepDiffMapper.map( | |
{$$hashKey:'testId', obj1:'test', obj3:{test1:'test', test2:{a:1, b:2} } }, | |
{$$hashKey:'testId', obj1:'test', obj3:{test1:'test', test2:{a:1} } } | |
); | |
console.log(result); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment