將兩個陣列合併為鍵值對
當我們有兩個獨立的陣列並且我們想要從這兩個陣列中建立鍵值對時,我們可以使用陣列的 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"
}