如何将数组[aaa,bbb,ccc]转换为[[aaa],[bbb],[ccc]]

时间:2019-09-20 11:59:53

标签: google-apps-script google-sheets-macros

我有:

var array1 = [[aaa],[bbb]]; //SpreadsheetApp.getActiveSheet().getRange('A2:A').getValues();
var array2 = [[ccc],[vvv],[fff]]; //SpreadsheetApp.getActiveSheet().getRange('B2:B').getValues();

然后我连接数组:

const newArray = [];

array1.forEach( function(item1) {
  array2.forEach( function(item2) {
    newArray.push(item1 + " " + item2)
  })
});

此功能的结果:

Logger.log(newArray);
//[aaa ccc, aaa vvv, aaa fff, bbb ccc, bbb vvv, bbb fff]

如何将结果转换为下一个?

[[aaa ccc], [aaa vvv], [aaa fff], [bbb ccc], [bbb vvv], [bbb fff]]

我需要这样将值放在一列中:

sheet.getRange('D2:D').setValues(newArray)

否则,将显示错误:无法将数组转换为数字[] []

1 个答案:

答案 0 :(得分:2)

改为推送数组:

var array1 = [["aaa"],["bbb"]]; //SpreadsheetApp.getActiveSheet().getRange('A2:A').getValues();
var array2 = [["ccc"],["vvv"],["fff"]]; //SpreadsheetApp.getActiveSheet().getRange('B2:B').getValues();


const newArray = [];

array1.forEach( function(item1) {
  array2.forEach( function(item2) {
    newArray.push([item1 + " " + item2])
  })
});
console.log(newArray)