-
-
Save Uvacoder/ab9dbdd1ae44061b8ba7ea9f4be36186 to your computer and use it in GitHub Desktop.
Shallow compare objects and get diffs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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