在 JavaScript 中按列将数组合并到另一个数组
javascriptweb developmentfront end technologyobject oriented programming
假设我们有三个数字数组,如 −
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 } ]