티스토리 뷰
JSON.stringify
을 사용하지 않고 두 Object가 같은지 비교(deep-equal)
Deep Equality checking of Two Objects
function compareObjectsDeepEqual(original, target) {
const isObject = obj => typeof obj === "object" && obj !== null;
if (!isObject(original) || !isObject(target)) {
return original === target;
}
const keysOfOriginal = Object.keys(original);
const keysOfTarget = Object.keys(target);
if (keysOfOriginal.length !== keysOfTarget.length) {
return false;
}
for (let key of keysOfOriginal) {
if (!keysOfTarget.includes(key)) {
return false;
}
if (isObject(original[key])) {
if (!compareObjectsDeepEqual(original[key], target[key])) {
return false;
}
} else {
if (original[key] !== target[key]) {
return false;
}
}
}
return true;
}
🔽 테스트 케이스들
-
empty :
const original = {}, target = {}
▶ true -
falsy value :
const original = { name: "" }, target = { name: 0 }
▶ false -
nested ▶ true
const original = { name: "Judy", work: { company: "zootopia", since: { year: 2017, month: 1, day: 1 }, }, }; const target = { name: "Judy", work: { company: "zootopia", since: { year: 2017, month: 1, day: 1 }, }, };
-
null :
const original = { name: null }, target = { name: null })
▶ true -
Array : ▶ true
const original = { name: "Judy", array: ["0", "1", "2"] }; const target = { name: "Judy", array: ["0", "1", "2"] };
-
Array + Type of value ▶ false
const original = { name: "Judy", array: ["0", "1", "2"] }; const target = { name: "Judy", array: [0, 1, 2] };
-
Do not check for a property in the object's prototype chain ▶ false
Object.prototype.test = "Don't check me!"; const original = { name: "Judy", test: "Don't check me!" }; const target = { name: "Judy" };
-
Complex nested object + array ▶ true
const original = { name: "Judy", array: [{ A: "apple", B: ["beer", "blue"] }], string: "STRING ", }; const target = { name: "Judy", array: [{ A: "apple", B: ["beer", "blue"] }], string: "STRING ", };
-
Order of original and target (Two-way)
const original = original, target)
▶ falseconst original = target, original)
▶ falseconst original = { A: "apple", B: ["beer", "blue"], }; const target = { A: "apple", };
'공부 > JS' 카테고리의 다른 글
[JS/알고리즘] Sort Colors : Dutch national flag problem (0) | 2020.09.07 |
---|---|
[JS/알고리즘] Find First and Last Position of Element in Sorted Array (0) | 2020.09.07 |
[JS/알고리즘] Merge Two Sorted Lists (0) | 2020.09.07 |
[JS] Promise.all()은 병렬일까 직렬일까🤔 (1) | 2020.08.22 |
[JS] Prevent Stack Overflow (0) | 2020.08.06 |
댓글