如何使用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 }
]

更新時間:2020-10-10

851 次點選

開始你的職業生涯

完成課程即可獲得認證

立即開始
廣告
© . All rights reserved.