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