Posted By

tennison on 10/01/10


Tagged

js object compare


Versions (?)

compare 2 json objects returns an array of all differences


 / Published in: JavaScript
 

pass in 2 json objects returns an array of all differences included those nested in children.

_Q used internally to pass through to self, do not pass in _Q

  1. var compare = function (obj1, obj2, _Q){
  2. _Q = (_Q == undefined)? new Array : _Q;
  3.  
  4. function size(obj) {
  5. var size = 0;
  6. for (var keyName in obj){
  7. if(keyName != null) size++;
  8. }
  9. return size;
  10. };
  11.  
  12. if (size(obj1) != size(obj2)) {
  13. //console.log('JSON compare - size not equal > '+keyName)
  14. };
  15.  
  16. var newO2 = jQuery.extend(true, {}, obj2);
  17.  
  18. for(var keyName in obj1){
  19. var value1 = obj1[keyName],
  20. value2 = obj2[keyName];
  21.  
  22. delete newO2[keyName];
  23.  
  24. if (typeof value1 != typeof value2 && value2 == undefined) {
  25. _Q.push(['missing', keyName, value1, value2, obj1])
  26. }else if (typeof value1 != typeof value2) {
  27. _Q.push(['diffType', keyName, value1, value2, obj1])
  28. }else{
  29. // For jQuery objects:
  30. if (value1 && value1.length && (value1[0] !== undefined && value1[0].tagName)) {
  31. if (!value2 || value2.length != value1.length || !value2[0].tagName || value2[0].tagName != value1[0].tagName) {
  32. _Q.push(['diffJqueryObj', keyName, value1, value2, obj1])
  33. }
  34. }else if(value1 && value1.length && (value1.tagName !== value2.tagName)){
  35. _Q.push(['diffHtmlObj', keyName, value1, value2, obj1])
  36. }else if (typeof value1 == 'function' || typeof value2 == 'function') {
  37. _Q.push(['function', keyName, value1, value2, obj1])
  38. }else if(typeof value1 == 'object'){
  39. var equal = Arcadia.Utility.CompareJson(value1, value2, _Q);
  40. }else if (value1 != value2) {
  41. _Q.push(['diffValue', keyName, value1, value2, obj1])
  42. }
  43. };
  44. }
  45.  
  46. for(var keyName in newO2){
  47. _Q.push(['new', keyName, obj1[keyName], newO2[keyName], newO2])
  48. }
  49.  
  50. /*
  51. */
  52. return _Q;
  53. }; // END compare()

Report this snippet  

You need to login to post a comment.