สมมติเรามี JSON Object สองตัวแบบนี้:
const obj1 = {a: "apple", b: "banana", c: "carrot"};
const obj2 = {a: "apple", e: "egg", b: "banana", c: "carrot", d: "dog"};
เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่รับออบเจกต์ทั้งสองเข้ามา เราต้องการตรวจสอบ Boolean ว่าทั้งสองออบเจกต์ตรงกันหรือไม่ โดยไม่ต้องลบข้อมูลจากออบเจกต์ใดๆ
ตัวอย่าง: ถ้าใช้ข้อมูลข้างต้น Boolean check ควรคืน true เพราะค่าของคีย์ที่มีในทั้งสองออบเจกต์ตรงกัน
แต่ถ้า obj1 เหมือนเดิม แต่อบเจกต์ obj2 เป็น:
const obj1 = {a: "apple", b: "banana", c: "carrot"}
const obj2 = {a: "ant", e: "egg", b: "banana", c: "carrot", d: "dog"}
ควรคืน false เพราะค่าของคีย์ 'a' ไม่ตรงกัน แม้คีย์อื่นจะตรงและบางคีย์ไม่มีในทั้งสอง
ตัวอย่างโค้ด
const obj1 = {
a: "apple",
b: "banana",
c: "carrot"
}
const obj2 = {
a: "apple",
b: "banana",
c: "carrot",
d: "dog",
e: "egg"
}
const obj3 = {a: "apple", b: "banana", c: "carrot"}
const obj4 = {a: "ant", e: "egg" ,b: "banana", c: "carrot", d: "dog"}
function checkEquality(a, b) {
const entries1 = Object.entries(a);
const entries2 = Object.entries(b);
const short = entries1.length > entries2 ? entries2 : entries1;
const long = short === entries1 ? b : a;
const isEqual = short.every(([k, v]) => long[k] === v);
return isEqual;
}
console.log(checkEquality(obj1, obj2))
console.log(checkEquality(obj3, obj4))
ผลลัพธ์
ผลลัพธ์ที่แสดงในคอนโซลจะเป็นดังนี้:
true false