假设我们有三个这样的数字数组-
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 } ]