我有一个看起来像这样的电子表格
+------+-----------------------------+
| Col1 | Col2 |
+------+-----------------------------+
| Joe | pepperoni, sausage, peppers |
| Bill | pepperoni, onions |
+------+-----------------------------+
我想将电子表格转换为:
Pepperoni: Joe, Bill
Sausage: Joe
Peppers: Joe
Onions: Bill
我没有在GAS中看到一种简单的方法。有吗?
答案 0 :(得分:1)
你可以用一个对象来实现:
var obj = {};
解析for循环中的每一行:
for (var i=0; i<data.length; i++ ) { ....
对于每一行,取col2并将调味品分成一个数组:
var condiments = data[i][1].split(",") // [1] == Col2 index
循环通过每个调味品:
for (var c=0; c<condiments.length; c++) { ....
使用调味品更改obj
这是魔法:
obj[condiments[c]] = obj[condiments[c]] || []; // vodoo magik
obj[condiments[c]].push(data[i][0]); // [0] == Col1 index , standard magik
然后解析obj以使用它重建表。
完整的脚本看起来像这样:
function parsePizzas(){
var obj = {};
var data = SpreadsheetApp.getActive().getRange("A2:B").getValues();
for(var i = 0; i<data.length; i++) {
if(data[i][0] == "") {
continue; // skip empty rows
}
var condiments = data[i][1];
condiments = condiments.split(",");
for (var k = 0;k<condiments.length; k++) {
obj[condiments[k]] = obj[condiments[k]] || [];
obj[condiments[k]].push(data[i][0]);
}
}
var out = [];
for (var o in obj) {
out.push([o, obj[o]]); // o == object name, obj[o] == objec value
}
return out;
}