Chris de Jong
Chris de Jong

Reputation: 21

Storing an array of values from Docs in Google Apps Scripts

I'm a beginner working with Google Apps Script to pull data from a Google Doc, and I need some help...

I have a Google Doc that has a ton of cooking recipes. I'd like to write a function that randomly selects 4 recipes, and emails me the ingredients so I know what to shop for that week. All my recipes titles are 'Heading 3', with the ingredients as bullet points below them. I'm fully open to modifying the formatting if need be.

I think I have a way to identify all text that is of type 'Heading 3', but I need a way to store them in an array as text, to then randomly select 4 of them. I can't seem to solve this...

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

Upvotes: 0

Views: 201

Answers (1)

Cooper
Cooper

Reputation: 64100

The first function generates an array of objects from your document

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

Requires Chrome V8

Upvotes: 1

Related Questions