Giả sử chúng ta có ba mảng số như sau:
const code = [123, 456, 789]; const year = [2013, 2014, 2015]; const period = [3, 4, 5];
Chúng ta cần viết hàm JavaScript nhận vào ba mảng này. Hàm xây dựng mảng đối tượng dựa trên ba mảng này như sau:
const output = [
{"code": 123, "year": 2013, "period": 3},
{"code": 456, "year": 2014, "period": 4},
{"code": 789, "year": 2015, "period": 5}
];Ví dụ
Mã thực hiện:
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));Kết quả
Kết quả in ra console:
[
{ code: 123, year: 2013, period: 3 },
{ code: 456, year: 2014, period: 4 },
{ code: 789, year: 2015, period: 5 }
]