Skip to content

Instantly share code, notes, and snippets.

@nazreen
Created November 18, 2017 15:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nazreen/3075db249d78507b53c96b9104aa597a to your computer and use it in GitHub Desktop.
Save nazreen/3075db249d78507b53c96b9104aa597a to your computer and use it in GitHub Desktop.
Javascript utility function to compare 2 objects.
function logDifference(arr1, arr2) {
let difference = arr1.filter(
x => arr2.indexOf(x) == -1)
.concat(arr2.filter(
x => arr1.indexOf(x) == -1)
);
if (difference.length < 1) return []; // if no difference return empty array
return difference;
console.log(difference)
};
function areObjectsSimilar(obj1, obj2) {
const differences = [];
const obj1Keys = Object.keys(obj1);
const obj2Keys = Object.keys(obj2);
const obj1Length = obj1Keys.length;
const obj2Length = obj2Keys.length;
// check if equal number of properties
if(obj1Length !== obj2Length) {
differences.push(`Not equal number of properties`);
}
const differentProps = logDifference(obj1Keys, obj2Keys);
if(differentProps.length > 0) differences.push(`These properties exist only in one of the objects: ${differentProps.join()}`);
// determine which object should be the sample
function whichLonger(first, second) {
const firstLength = Object.keys(first).length;
const secondLength = Object.keys(second).length;
if(firstLength > secondLength) return first;
if(secondLength > firstLength) return second;
return first
}
const sampleObject = whichLonger(obj1, obj2);
const sampleKeys = Object.keys(sampleObject);
// comapre value of each
sampleKeys.forEach((key) => {
if(obj1[key] == obj2[key]) {
// console.log(`SIMILAR: ${key} for both are the same`);
} else {
console.log(`DIFFERENT: ${obj1.constructor.name}'s ${key} is ${obj1[key]} while second object's ${key} is ${obj2[key]}`);
differences.push(`DIFFERENT: first object's ${key} is ${obj1[key]} while second object's ${key} is ${obj2[key]}`)
}
});
if(differences.length > 0) {
console.log(`OBJECTS DO NOT HAVE EQUAL PROPERTIES. LIST OF DIFFERENCES: \n ${differences.join('\n\n')}`);
return false
} else {
console.log('objects have equal properties')
return true
}
};
export default areObjectsSimilar;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment