以列式将数组合并到 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