สมมติว่าเรามีสองอ็อบเจกต์ที่มีคู่ key-value คล้ายกัน แต่มี key หนึ่งหรือหลายตัวที่มีค่าต่างกัน หน้าที่คือเขียนฟังก์ชันรับสองอ็อบเจกต์ คืน key แรกที่พบว่ามีค่าต่างกัน ถ้าทุก key เหมือนกันหมด คืน -1
อ็อบเจกต์ตัวอย่าง
const obj1 = {
name: 'Rahul Sharma',
id: '12342fe4554ggf',
isEmployed: true,
age: 45,
salary: 190000,
job: 'Full Stack Developer',
employedSince: 2005
}
const obj2 = {
name: 'Rahul Sharma',
id: '12342fe4554ggf',
isEmployed: true,
age: 45,
salary: 19000,
job: 'Full Stack Developer',
employedSince: 2005
}
เราจะรับสองอ็อบเจกต์ วนลูปผ่านอันแรกด้วย forEach() ตรวจสอบความเท่ากันในทั้งสอง ถ้าค่าที่ไหนไม่ตรง จะอัปเดต flag ออกจากลูป และคืน key นั้น ถ้าวนจบลูป หมายถึงทุกอย่างตรงกัน คืน -1
โค้ดเต็ม
ตัวอย่าง
const obj1 = {
name: 'Rahul Sharma',
id: '12342fe4554ggf',
isEmployed: true,
age: 45,
salary: 190000,
job: 'Full Stack Developer',
employedSince: 2005
}
const obj2 = {
name: 'Rahul Sharma',
id: '12342fe4554ggf',
isEmployed: true,
age: 45,
salary: 19000,
job: 'Full Stack Developer',
employedSince: 2005
}
const difference = (obj1, obj2) => {
let keyFound = false;
Object.keys(obj1).forEach(key => {
if(obj1[key] !== obj2[key]){
return keyFound = key;
}
});
return keyFound || -1;
};
console.log(difference(obj1, obj2));
ผลลัพธ์
ผลลัพธ์ในคอนโซลจะเป็น
salary