Skip to content

Instantly share code, notes, and snippets.

@PatrickYeungts
Forked from Yimiprod/difference.js
Created March 6, 2024 02:14
Show Gist options
  • Save PatrickYeungts/a1690da45e740059a2a9c8ef34ad938c to your computer and use it in GitHub Desktop.
Save PatrickYeungts/a1690da45e740059a2a9c8ef34ad938c to your computer and use it in GitHub Desktop.
Deep diff between two object, using lodash
/**
* This code is licensed under the terms of the MIT license
*
* Deep diff between two object, using lodash
* @param {Object} object Object compared
* @param {Object} base Object to compare with
* @return {Object} Return a new object who represent the diff
*/
function difference(object, base) {
function changes(object, base) {
return _.transform(object, function(result, value, key) {
if (!_.isEqual(value, base[key])) {
result[key] = (_.isObject(value) && _.isObject(base[key])) ? changes(value, base[key]) : value;
}
});
}
return changes(object, base);
}
@PatrickYeungts
Copy link
Author

/**
 * This code is licensed under the terms of the MIT license
 * from https://gist.github.com/Yimiprod/7ee176597fef230d1451
 *
 * Deep diff between two object, using lodash
 *
 * updated with:
 * before diff the object compared will be normalized to base
 *
 * @param  {Object} object Object compared
 * @param  {Object} base   Object to compare with
 * @return {Object}        Return a new object who represent the diff
 */
function difference(object, base) {
  if (!base || !object) return object ?? base;
  function normalize(object, base) {
    return !_.isArray(object) ? [...new Set([...Object.keys(object), ...Object.keys(base)])].reduce(
      (acc, key) => ({ ...acc, [key]: object[key] }),
      {}
    ) : object;
  }

  function changes(object, base) {
    return _.transform(object, function (result, value, key) {
      if (!_.isEqual(value, base[key])) {
        result[key] =
          _.isObject(value) && _.isObject(base[key])
            ? changes(normalize(value, base[key]), base[key])
            : value;
      }
    });
  }
  return changes(normalize(object, base), base);
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment