Skip to content

Instantly share code, notes, and snippets.

@joe-oli
Created January 31, 2020 02:43
Show Gist options
  • Save joe-oli/68ff5ac848e96dfe31ec6b3abf37b89b to your computer and use it in GitHub Desktop.
Save joe-oli/68ff5ac848e96dfe31ec6b3abf37b89b to your computer and use it in GitHub Desktop.
shallow compare 2 javascript JS objects
const shallowCompareFN = (obj1, obj2) =>
Object.keys(obj1).length === Object.keys(obj2).length &&
Object.keys(obj1).every(key =>
obj2.hasOwnProperty(key) && obj1[key] === obj2[key]
);
let obj1 = {
prop1 : 'abc',
prop2 : '123'
}
let obj2 = {
prop1 : 'abc',
prop2 : '123'
}
/*
obj1 == obj2 <-- false;
obj1 === obj2 <-- false
shallowCompareFN(obj1,obj2) <-- true
*/
//Now if you set
let obj3 = obj2;
obj3.prop1 = 'changed';
/*
obj3 == obj2 <-- true; obviously, same object.
BUT shallowCompareFN(obj1,obj2) <-- false, because changing obj3 affects obj2;
unless the assignment was destructured i.e. let obj3 = {...obj2}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment