Created
January 31, 2020 02:43
-
-
Save joe-oli/68ff5ac848e96dfe31ec6b3abf37b89b to your computer and use it in GitHub Desktop.
shallow compare 2 javascript JS objects
This file contains hidden or 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 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