สมมติเรามีออบเจ็กต์แบบนี้:
const obj = { name: "Jai", age: 32, occupation: "Software Engineer", address: "Dhindosh, Maharasthra", salary: "146000" };เราต้องเขียนฟังก์ชันที่รับออบเจ็กต์ที่มีคีย์-ค่าและแปลงเป็น Map
ตัวอย่าง
โค้ดสำหรับนี้:
const obj = { name: "Jai", age: 32, occupation: "Software Engineer", address: "Dhindosh, Maharasthra", salary: "146000" }; const objectToMap = obj => { const keys = Object.keys(obj); const map = new Map(); for(let i = 0; i < keys.length; i++){ map.set(keys[i], obj[keys[i]]); }; return map; }; console.log(objectToMap(obj));ผลลัพธ์
ผลลัพธ์ในคอนโซล:
Map(5) { 'name' => 'Jai', 'age' => 32, 'occupation' => 'Software Engineer', 'address' => 'Dhindosh, Maharasthra', 'salary' => '146000' }