สร้าง Reverse Map จาก Object: Key ↔ Value สลับกัน เพื่อค้นหา Key จาก Value ได้เร็ว
ตัวอย่าง
{ Pineapple: 38, Apple: 110, Pear: 109 }
→ Find Key by Value: findKey(110) → 'Apple'
ตัวอย่างโค้ด
const products = { Pineapple: 38, Apple: 110, Pear: 109 };
const findKey = (obj, val) => {
const reversed = Object.keys(obj).reduce((acc, key) => {
acc[obj[key]] = key;
return acc;
}, {});
return reversed[val] || false;
};
console.log(findKey(products, 110));
ผลลัพธ์
Apple
วิธีแบบ Map (รองรับ Value ซ้ำได้)
const createReverseMap = obj => {
const map = new Map();
for (const [key, value] of Object.entries(obj)) {
if (!map.has(value)) map.set(value, []);
map.get(value).push(key);
}
return map;
};
const reverseMap = createReverseMap(products);
console.log(reverseMap.get(110)); // ['Apple']
ถ้า Value อาจซ้ำ ให้เก็บเป็น Array of Keys