9

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?

Rubén
  • 34,714
  • 9
  • 70
  • 166
LondonRob
  • 73,083
  • 37
  • 144
  • 201

2 Answers2

17

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 :

enter image description here

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

Community
  • 1
  • 1
Serge insas
  • 45,904
  • 7
  • 105
  • 131
5

With V8 runtime:

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

for (const [key, value] of Object.entries(dict)) {
  Logger.log(`${key}: ${value}`);
}
Ivan
  • 51
  • 1
  • 6