Хранение массива значений из документов в скриптах Google Apps - PullRequest
0 голосов
/ 05 августа 2020

Я новичок, работаю с Google Apps Script для извлечения данных из Google Do c, и мне нужна помощь ...

У меня есть Google Do c, в котором много рецептов приготовления. Я хотел бы написать функцию, которая случайным образом выбирает 4 рецепта и присылает мне ингредиенты по электронной почте, чтобы я знал, что покупать на этой неделе. Все мои рецепты названы «Заголовком 3», а ингредиенты помечены списком под ними. Я полностью готов изменить форматирование, если это необходимо. текст, чтобы затем случайным образом выбрать 4 из них. Кажется, я не могу решить эту проблему ...

function onOpen() {
  var ui = DocumentApp.getUi();
  ui.createMenu('Generate Weekly Shopping List')
      .addItem('Send Email', 'generateMenu')
      .addToUi();
}

function generateMenu() {
  var ps = DocumentApp.getActiveDocument().getBody()
  var searchType = DocumentApp.ElementType.PARAGRAPH;
  var searchHeading = DocumentApp.ParagraphHeading.HEADING3;
  var searchResult = null;

  while (searchResult = ps.findElement(searchType, searchResult)) {
    var par = searchResult.getElement().asParagraph();
    if (par.getHeading() == searchHeading) {
      // Found one, update Logger.log and stop.
      var h = searchResult.getElement().asText().getText();

      return h; 
    //how do I store this back into an array...then randomly select 4?
    }  
 
  // Get the email address of the active user - that's you.
  var email = Session.getActiveUser().getEmail();

  // Send yourself an email with a link to the document.
  GmailApp.sendEmail(email, "Shopping List For The Week", "Here is the shopping list:" + h);
  
  }
}

1 Ответ

1 голос
/ 05 августа 2020

Первая функция генерирует массив объектов из вашего документа

function generateObj() {
  var body = DocumentApp.getActiveDocument().getBody()
  var children=body.getNumChildren();
  //var html='';
  var rObj={rA:[]}
  for(var i=0;i<children;i++) {
    var child=body.getChild(i);
    if(child.getType()==DocumentApp.ElementType.PARAGRAPH && child.asParagraph().getHeading()==DocumentApp.ParagraphHeading.HEADING3 && child.asParagraph().getText().length>0) {
      //html+='<br />' + child.asParagraph().getText();
      var prop=child.asParagraph().getText();
      rObj.rA.push(prop);
      rObj[prop]=[];
      var n=1;
      while(body.getChild(i+n).getType()==DocumentApp.ElementType.LIST_ITEM) {
        //html+='<br />'+body.getChild(i+n).asListItem().getText();
        rObj[prop].push(body.getChild(i+n).asListItem().getText());
        n++;
      }
      i+=n-1;
    } 
  }
  //DocumentApp.getUi().showModelessDialog(HtmlService.createHtmlOutput(html), 'Results')
  return rObj;
}

//defaults to 4 selections 
function pikn(n=4) {
  var rObj=generateObj();//get array of objects
  var rA=[];
  var t=rObj.rA.slice();//copy array to temp array
  for(var i=0;i<n;i++) {
    var idx=Math.floor(Math.random()*t.length);//pick random index
    rA.push(t[idx]);//save title of recipe
    t.splice(idx,1);//remove that index
  }
  var s='';
  //loop through selected recipes which are also object properties
  rA.forEach(function(r,i){
    var items=rObj[r];
    s+='\n' + r;
    items.forEach(function(item,j){s+='\n' + item});//loop through recipe items and collect everything in s as simple text to insert into standard body
  });
  GmailApp.sendEmail("Your email address","Random Recipes",s);
}

Требуется Chrome V8

...