将两个数组合并为键值对
当我们有两个独立的数组并且我们想要从这两个数组中创建键值对时,我们可以使用数组的 reduce 函数,如下所示:
var columns = ["Date", "Number", "Size", "Location", "Age"];
var rows = ["2001", "5", "Big", "Sydney", "25"];
var result = rows.reduce(function(result, field, index) {
result[columns[index]] = field;
return result;
}, {})
console.log(result);
输出:
{
Date: "2001",
Number: "5",
Size: "Big",
Location: "Sydney",
Age: "25"
}