简体   繁体   中英

Combining Two Arrays To One in NodeJS

I want to create Excel file that consist of 2 arrays of data with ExcelJS.

I can create the Excel file:

var Excel = require('exceljs');
var workbook = new Excel.Workbook();
var sheet = workbook.addWorksheet('My Sheet', {properties:{tabColor:{argb:'FFC0000'}}});

I can add column headers:

sheet.columns = [{key:"date", header:"Date"}, {key: "quantity", header: "Quantity"}]

I got 2 arrays for these columns:

array_date = [2018-01-04, 2018-01-06, 2018-01-08, 2018-01-09]
array_quantity = [25, 32, 54, 48]

I want to combine these 2 arrays to one array like this:

var merged = [{date:"2018-01-04", quantity:25} 
          , {date:"2018-01-06", quantity:32}  
          , {date:"2018-01-08", quantity:42} 
          , {date:"2018-01-09", quantity:48}];

If I can combine, I able to add as row for every data:

for(i in merged){
  sheet.addRow(merged[i]);
}

Then I can create the Excel File:

workbook.xlsx.writeFile("some.xlsx").then(function() {
console.log("xls file is written.");
});

How can I combine two arrays to one If they are ordered? Also, I'm wondering is this the best approach to create excel file in NodeJS?

You can create the new array with

var array_date = ["2018-01-04", "2018-01-06", "2018-01-08", "2018-01-09"];
var array_quantity = [25, 32, 54, 48];

var merged = array_date.map((date, i) => ({
    date,
    quantity: array_quantity[i],
}));
array_date = [2018-01-04, 2018-01-06, 2018-01-08, 2018-01-09]
array_quantity = [25, 32, 54, 48]

var merged=[];

for(var i=0;i<array_date.length;i++){
  merged.push({date:array_date[i], quantity:array_quantity[i]});
}

console.log(merged);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM