简体   繁体   English

在NodeJS中将两个数组组合为一个

[英]Combining Two Arrays To One in NodeJS

I want to create Excel file that consist of 2 arrays of data with ExcelJS. 我想用ExcelJS创建包含2个数据数组的Excel文件。

I can create the Excel file: 我可以创建Excel文件:

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: 这些列有2个数组:

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: 我想将这2个数组合并为一个数组,如下所示:

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: 然后,我可以创建Excel文件:

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? 另外,我想知道这是在NodeJS中创建excel文件的最佳方法吗?

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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