สมมติว่าเรามีอาร์เรย์ของอาร์เรย์เช่นนี้ −
const arr = [ [ ['juice', 'apple'], ['maker', 'motts'], ['price', 12] ], [ ['juice', 'orange'], ['maker', 'sunkist'], ['price', 11] ] ];
เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่รับอาร์เรย์ดังกล่าวและส่งกลับอาร์เรย์ของออบเจ็กต์ที่สร้างขึ้นตามอาร์เรย์อินพุต
ดังนั้น สำหรับอาร์เรย์ด้านบน ผลลัพธ์ควรมีลักษณะดังนี้ −
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 }
][
{ juice: 'apple', maker: 'motts', price: 12 },
{ juice: 'orange', maker: 'sunkist', price: 11 }
]