Last active
May 18, 2022 12:24
-
-
Save adamwdennis/7e5819c16bba48b8861477fb161752c0 to your computer and use it in GitHub Desktop.
Comparing two objects for additions, deletions, and updates.
This file contains 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 existingFields = [ | |
{ | |
id: "1", | |
name: "", | |
value: "6.2%", | |
related_id: "1", | |
}, | |
{ | |
id: "3", | |
name: "", | |
value: "5.0%", | |
related_id: "1", | |
}, | |
{ | |
id: "4", | |
name: "", | |
value: "25", | |
related_id: "7", | |
}, | |
]; | |
const inputFields = [ | |
{ | |
id: "1", | |
name: "", | |
value: "6.3%", | |
related_id: "1", | |
}, | |
{ | |
id: "3", | |
name: "", | |
value: "5.0%", | |
related_id: "1", | |
}, | |
{ | |
value: "25", | |
related_id: "7", | |
}, | |
]; | |
const onlyInLeft = (left, right, compareFunction) => | |
left.filter( | |
(leftValue) => | |
!right.some((rightValue) => compareFunction(leftValue, rightValue)) | |
); | |
const isSameField = (a, b) => a.id === b.id && a.related_id === b.related_id; | |
const inBothWithUpdate = (l, r, compareFunction) => | |
l.filter((a) => | |
r.some( | |
(b) => | |
compareFunction(a,b) | |
) | |
); | |
const isSameFieldButWithUpdatedValues = (a, b) => | |
isSameField(a,b) && | |
(a.name !== b.name || a.value !== b.value); | |
const onlyInExisting = onlyInLeft(existingFields, inputFields, isSameField); | |
console.log(`toBeRemoved: ${JSON.stringify(onlyInExisting)}`) | |
const onlyInInput = onlyInLeft(inputFields, existingFields, isSameField); | |
console.log(`toBeAdded: ${JSON.stringify(onlyInInput)}`) | |
const inBothToBeUpdated = inBothWithUpdate(inputFields, existingFields, isSameFieldButWithUpdatedValues) | |
console.log(`toBeUpdated: ${JSON.stringify(inBothToBeUpdated)}`) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment