有没有一种方法可以将表单中的所有字段收集到2D数组中以写入Google表格?

时间:2019-08-23 22:47:34

标签: multidimensional-array google-apps-script google-sheets

目标:我希望使用Google App脚本创建自定义表单,以将具有不同行数的数据提交给Google表格。从本质上讲,将有一些基本字段,但是然后有一个表结构,用户将可以按一个按钮在表的末尾添加另一行。他们提交表单后,结果将被添加到Google工作表中。

到目前为止,我已经创建了表单,它允许您添加2个包含字段的div。我不想手动将每个字段映射到一个数组中以将其发送给Google,所以我正在寻找最干净的方法。 我试图一次提取所有表单字段,并考虑按班级提取它们。我在将2D数组写入表格的位置时遇到问题,但是在获取数据时遇到了问题。

'''html
<form id="soulTestForm">

<div class="block">
 <div>
 <label for="name1">Name</label>
 <input type="text" name="name1" id="name1" placeholder="A Fancy Name">
 </div>

<div>
    <label for="count1">Count</label>    
    <input type="number" name="count1" id="count1" placeholder="100">
</div>
</div>
<div class="block">
 <div>
 <label for="name2">Name</label>
 <input type="text" name="name2" id="name2" placeholder="A Fancy Name">
 </div>

<div>
    <label for="count2">Count</label>    
    <input type="number" name="count2" id="count2" placeholder="100">
</div>
</div>
  <button type="button" name="addSection" id="addSection" value="Add an Entry" onclick="addBlock();" >Add a Section</button>
 <input type="submit" onclick="this.value='Magic ...'; google.script.run.withSuccessHandler(formSubmitted) .writeForm(this.parentNode); return false;">
</form>
<script>
function addBlock() {
  var block = document.getElementsByClassName('soulBlocks');
  var i;
  for (i = 0; i < block.length; i++){
    console.log("i=" + i);
    if (block[i].style.display=="none"){
      console.log("block if");
      block[i].style.display="block";
      if (i == block.length-1) {
        document.getElementById("addSection").style.visibility="hidden";
        }
      break;
    }      
  } 
}
</script>


'''Code.gs file
function writeForm(form) {
var fields = [
 [form.name1, form.count1],
 [form.name2, form.count2]
 ]; 
}

1 个答案:

答案 0 :(得分:2)

流量:

  • 使用form来获取Object.keys对象的所有键作为数组
  • 使用Array.reduce
  • 将键数组拆分为两个一组

摘要:

function writeForm(form) {
  var tempArr,val;
  var arr2d = Object.keys(form).reduce(function(acc,curr,i){
    val = form[curr];
    i % 2 === 0 ? (tempArr= [val]) : (tempArr.push(val), acc.push(tempArr));
    return acc;
  },[]);
  return arr2d;
}
console.log(writeForm({"name1":"Cat","count1":"100","name2":"Mouse","count2":"99"}))