Iterate over an object in Google Apps script

2019-02-25 08:06发布

问题:

I thought my question would be answered with this or this but neither is what I'm looking for.

I have an object in Google Script, and want to iterate over each element:

var dict = {
    "foo": "a",
    "bar": "b"
};

for each key, element in dict{
    print the key and the element
}

Is this possible?

回答1:

I usually do something like that :

var dict = {
    "foo": "a",
    "bar": "b"
};

function showProperties(){
  var keys = [];
  for(var k in dict) keys.push(k+':'+dict[k]);
  Logger.log("total " + keys.length + "\n" + keys.join('\n'));
}

result in Logger :

You get the logger in the script editor/view/Logs