Created
August 16, 2023 07:50
-
-
Save dominicgan/d136675fbddff636bfb376054c12fec2 to your computer and use it in GitHub Desktop.
Compare two key:value arrays and list differences
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
function compareSelectedKeysWithValues(object1, object2, keysToCompare) { | |
const result = {}; | |
keysToCompare.forEach(key => { | |
const arr1 = object1[key] || []; | |
const arr2 = object2[key] || []; | |
const added = arr2.filter(item2 => !arr1.some(item1 => Object.keys(item1)[0] === Object.keys(item2)[0])); | |
const deleted = arr1.filter(item1 => !arr2.some(item2 => Object.keys(item2)[0] === Object.keys(item1)[0])); | |
const modified = arr1.filter(item1 => | |
arr2.some(item2 => | |
Object.keys(item1)[0] === Object.keys(item2)[0] && item1[Object.keys(item1)[0]] !== item2[Object.keys(item2)[0]] | |
) | |
).map(item1 => { | |
const item2 = arr2.find(item2 => Object.keys(item1)[0] === Object.keys(item2)[0]); | |
return { old: { [Object.keys(item1)[0]]: item1[Object.keys(item1)[0]] }, new: { [Object.keys(item2)[0]]: item2[Object.keys(item2)[0]] } }; | |
}); | |
result[key] = { | |
added, | |
deleted, | |
modified | |
}; | |
}); | |
return result; | |
} | |
// Example objects | |
const oldObject = { | |
EDUCATION: [ | |
{ A: 'Apple' }, | |
{ B: 'Bear' } | |
], | |
SCHOOL: [ | |
{ C: 'cat' }, | |
{ D: 'dat' } | |
] | |
}; | |
const newObject = { | |
EDUCATION: [ | |
{ A: 'Apple' }, | |
{ B: 'Bird' } | |
], | |
SCHOOL: [ | |
{ C: 'cat' }, | |
{ D: 'dot' } | |
] | |
}; | |
const keysToCompare = ['EDUCATION', 'SCHOOL']; | |
const comparisonResult = compareSelectedKeysWithValues(oldObject, newObject, keysToCompare); | |
console.log(comparisonResult); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment