สมมติเรามีอาร์เรย์ของอาร์เรย์แบบนี้:
const arr = [ [ [ 'juice', 'apple' ], [ 'maker', 'motts' ], [ 'price', 12 ] ], [ [ 'juice', 'orange' ], [ 'maker', 'sunkist' ], [ 'price', 11 ] ] ];
เราต้องเขียนฟังก์ชันที่รับอาร์เรย์แบบนี้และคืนค่าอาร์เรย์ของออบเจ็กต์ที่สร้างขึ้นจากอาร์เรย์นำเข้า
ผลลัพธ์ควรเป็น:const output = [ {juice: 'apple', maker: 'motts', price: 12}, {juice: 'orange', maker: 'sunkist', price: 11} ];ตัวอย่าง
โค้ดสำหรับนี้:
const arr = [ [ [ 'juice', 'apple' ], [ 'maker', 'motts' ], [ 'price', 12 ] ], [ [ 'juice', 'orange' ], [ 'maker', 'sunkist' ], [ 'price', 11 ] ] ]; const arrayToObject = arr => { let res = []; res = arr.map(list => { return list.reduce((acc, val) => { acc[val[0]] = val[1]; return acc; }, {}); }); return res; }; console.log(arrayToObject(arr));ผลลัพธ์
ผลลัพธ์ในคอนโซล:
[ { juice: 'apple', maker: 'motts', price: 12 }, { juice: 'orange', maker: 'sunkist', price: 11 } ]