Skip to content

Instantly share code, notes, and snippets.

@adamwdennis
Last active May 18, 2022 12:24
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adamwdennis/7e5819c16bba48b8861477fb161752c0 to your computer and use it in GitHub Desktop.
Save adamwdennis/7e5819c16bba48b8861477fb161752c0 to your computer and use it in GitHub Desktop.
Comparing two objects for additions, deletions, and updates.
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