Skip to content

Instantly share code, notes, and snippets.

@Uvacoder
Forked from DavidWells/compare-objects.js
Created January 2, 2022 18:41
Show Gist options
  • Select an option

  • Save Uvacoder/ab9dbdd1ae44061b8ba7ea9f4be36186 to your computer and use it in GitHub Desktop.

Select an option

Save Uvacoder/ab9dbdd1ae44061b8ba7ea9f4be36186 to your computer and use it in GitHub Desktop.
Shallow compare objects and get diffs
const isEqual = require('lodash.isequal')
function compareNewToOld(newValues, oldValues) {
const initialData = {
// default everything is equal
isEqual: true,
// Keys that are different
keys: [],
// Values of the keys that are different
diffs: {}
}
const newKeys = Object.keys(newValues)
const oldKeys = Object.keys(oldValues)
const set = new Set(newKeys.concat(oldKeys))
return Array.from(set).reduce((acc, current) => {
// if values not deep equal. There are changes
if (!isEqual(newValues[current], oldValues[current])) {
return {
isEqual: false,
keys: acc.keys.concat(current),
diffs: {
...acc.diffs,
...{
[`${current}`]: {
newValue: newValues[current],
oldValue: oldValues[current]
}
}
}
}
}
return acc
}, initialData)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment