สมมติว่าเรามีอ็อบเจกต์ดังนี้:
const products = {
"Pineapple":38,
"Apple":110,
"Pear":109
};Key ทั้งหมดไม่ซ้ำกัน และ Value ทั้งหมดก็ไม่ซ้ำกันเช่นกัน เราต้องเขียนฟังก์ชันที่รับค่า (value) เข้ามาและคืนค่า key ของมัน
เช่น: findKey(110) ควรคืนค่า:
"Apple"
เราจะแก้ปัญหานี้โดยการ reverse mapping ค่าเป็น key ก่อน แล้วค่อยใช้ object notation หาค่า
ตัวอย่าง
โค้ดต่อไปนี้เป็นตัวอย่าง:
const products = {
"Pineapple":38,
"Apple":110,
"Pear":109
};
const findKey = (obj, val) => {
const res = {};
Object.keys(obj).map(key => {
res[obj[key]] = key;
});
// ถ้าค่าไม่มีในอ็อบเจกต์ ให้คืน false
return res[val] || false;
};
console.log(findKey(products, 110));ผลลัพธ์
จะแสดงผลในคอนโซลดังนี้:
Apple