如何使用 JavaScript 中的 map() 和 reduce() 将数组转换为对象数组

javascriptweb developmentfront end technologyobject oriented programming更新于 2026/1/19 0:44:17

假设我们有一个像这样的数组数组 −

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 }
]

相关文章


有用资源