Skip to content

Instantly share code, notes, and snippets.

@codemilli
Last active February 11, 2016 15:34
Show Gist options
  • Save codemilli/40bb32d316624ccb877c to your computer and use it in GitHub Desktop.
Save codemilli/40bb32d316624ccb877c to your computer and use it in GitHub Desktop.
compare two object in javascript
const a = { blah: 1 };
const b = { blah: 1 };
const c = a;
const d = { blah: 2 };
const deepCompare = (obj1, obj2) => {
// 첫번째 오브젝트의 프로퍼티를 순회합니다.
for (var p in obj1) {
// 두 오브젝트 모두 가지고 있지 않는 프로퍼티이면 두 오브젝트는 같다고 할 수 없습니다.
if (obj1.hasOwnProperty(p) !== obj2.hasOwnProperty(p)) return false;
switch (typeof (obj1[p])) {
// object 이면 deepCompare 함수를 재귀적으로 호출합니다.
case 'object':
if (!deepCompare(obj1[p], obj2[p])) return false;
break;
// 함수이고 두번째 오브젝트도 가지고 있으면 toString 을 통하여 비교합니다.
case 'function':
if (typeof (obj2[p]) == 'undefined' ||
(p != 'compare' && obj1[p].toString() != obj2[p].toString())) return false;
break;
// 일반 값은 그냥 비교합니다.
default:
if (obj1[p] !== obj2[p]) return false;
}
}
// 두번째 오브젝트에 첫번째 오브젝트가 가지고 있지 않은 프로퍼티가 있는 체크합니다.
for (var p in obj2) {
if (typeof (obj1[p]) == 'undefined') return false;
}
// 모두 해당사항이 없으면 두 오브젝트는 같다고 할 수 있습니다.
return true;
};
console.log(deepCompare(a, b)); //true
console.log(deepCompare(a, c)); //true
console.log(deepCompare(a, d)); //false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment