Your report needs to ask every message in a list the same question. A for...of loop hands each message to that question, one at a time, without copying the question for every record.
Key Points
for (const message of messages) { ... }runs the block in curly braces once for each item inmessages, in the list’s order.- The name before
ofholds the current item on each pass. Here,messageis a whole record. It isn’t a number that counts the passes or marks a position. constfits because each pass gets a freshmessagethat never changes during that pass.- When the list runs out, the loop stops, and the code after its closing brace runs once.
- An
ifinside the loop asks your question on every pass, so only matching messages are selected. This version checks only the topic, so message 9’s pending label doesn’t keep it out. - An empty list means zero passes. The block never runs, there’s no error, and there’s no extra code for the empty case.
The Code
The console.log() lines are supplied so you can see which lines ran: