以列式將數組合併到 JavaScript 中的另一個數組中
假設我們有三個陣列的數字如下所示 -
const code = [123, 456, 789]; const year = [2013, 2014, 2015]; const period = [3, 4, 5];
我們需要編寫一個 JavaScript 函式,該函式採用三個這樣的陣列。然後,該函式應基於這三個陣列構造一個物件陣列,如下所示 -
const output = [
{"code": 123, "year": 2013, "period": 3},
{"code": 456, "year": 2014, "period": 4},
{"code": 789, "year": 2015, "period": 5}
];示例
程式碼將是 -
const code = [123, 456, 789];
const year = [2013, 2014, 2015];
const period = [3, 4, 5];
const mergeColumnWise = (code = [], year = [], period = []) => {
let results = [];
for(let i = 0; i < code.length; i++) {
results.push({
code: code[i],
year: year[i],
period: period[i]
});
}
return results;
};
console.log(mergeColumnWise(code, year, period));輸出
控制檯中的輸出將是 -
[
{ code: 123, year: 2013, period: 3 },
{ code: 456, year: 2014, period: 4 },
{ code: 789, year: 2015, period: 5 }
]
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
安卓
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP