1
0

object-diff.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. 'use strict';
  2. function objectDiff(first, second, path = '') {
  3. const diff = [];
  4. for (const key in first) {
  5. const a = first[key];
  6. const b = second[key];
  7. if (a === b) {
  8. continue;
  9. }
  10. if (b === undefined) {
  11. diff.push({path, key, values: [a], type: 'removed'});
  12. continue;
  13. }
  14. if (a && typeof a.filter === 'function' && b && typeof b.filter === 'function') {
  15. if (
  16. a.length !== b.length ||
  17. a.some((el, i) => {
  18. const result = !el || typeof el !== 'object'
  19. ? el !== b[i]
  20. : objectDiff(el, b[i], path + key + '[' + i + '].').length;
  21. return result;
  22. })
  23. ) {
  24. diff.push({path, key, values: [a, b], type: 'changed'});
  25. }
  26. } else if (typeof a === 'object' && typeof b === 'object') {
  27. diff.push(...objectDiff(a, b, path + key + '.'));
  28. } else {
  29. diff.push({path, key, values: [a, b], type: 'changed'});
  30. }
  31. }
  32. for (const key in second) {
  33. if (!(key in first)) {
  34. diff.push({path, key, values: [second[key]], type: 'added'});
  35. }
  36. }
  37. return diff;
  38. }