1

I have a simple JSON object:

"myObject": {
"var1": "analytics#filterExpression",
"var2": string,
"var3": string
}

How can I loop through this object, extract each variable name and pass them in my spreadsheet.

So far I'm doing this manually like this

sheet.appendRow(['var1', 'var3', 'var3']);

This is not very dynamic...

Simon Breton
  • 2,638
  • 7
  • 50
  • 105

1 Answers1

3

How about this sample script? In this sample, Object.keys is used.

Sample script:

// const string = "###";  // Please set "string".
// const sheet = ###;  // Please set "sheet".

const obj = {
  "myObject": {
    "var1": "analytics#filterExpression",
    "var2": string,
    "var3": string
  }
};
sheet.appendRow(Object.keys(obj.myObject));

Note:

  • About the order of each properties in the object of myObject,

    The iteration order for objects follows a certain set of rules since ES2015, but it does not (always) follow the insertion order. Ref

    • Please be careful this.
  • If you want to sort the values, please sort the values of Object.keys(obj.myObject) and put to the sheet.

    • It's like sheet.appendRow(Object.keys(obj.myObject).sort());

Reference:

Tanaike
  • 181,128
  • 11
  • 97
  • 165