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