如何使用JavaScript的map()和reduce()將陣列轉化為物件陣列
假設我們有一個這樣的陣列陣列 -
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 }
]
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C程式語言
C++
C#
MongoDB
MySQL
Javascript
PHP