compare 2 json对象返回一个包含所有差异的数组

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了compare 2 json对象返回一个包含所有差异的数组相关的知识,希望对你有一定的参考价值。

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()

以上是关于compare 2 json对象返回一个包含所有差异的数组的主要内容,如果未能解决你的问题,请参考以下文章

JavaComparable和Comparator接口的区别

Comparable接口

LeetCode 165 Compare Version Numbers(比较版本号)(string)(*)

Comparable 和 Comparator 接口是干什么的?

For 循环仅返回第一个 json 对象 Flutter

java Comparator.compare(T o1,To2) 返回负整数、正整数的意义