Two loops with output

#1

var i;
var j;
var nr = 1;

for (i = 0; i < msg.payload.TripList.Trip.length; i++) {
output = 'Verbindung ' + nr++;
for (j = 0; j < msg.payload.TripList.Trip[i].LegList[0].Leg.length; j++) {

  output += "\r\n-----\r\nZugtyp: " + msg.payload.TripList.Trip[i].LegList[0].Leg[j].$.name + 
        "\r\nStartbahnhof: " + msg.payload.TripList.Trip[i].LegList[0].Leg[j].Origin[0].$.name +
        "\r\nStartzeit: " + msg.payload.TripList.Trip[i].LegList[0].Leg[j].Origin[0].$.time + 
        "\r\nZielbahnhof: " + msg.payload.TripList.Trip[i].LegList[0].Leg[j].Destination[0].$.name + 
        "\r\nAnkuftszeit: " + msg.payload.TripList.Trip[i].LegList[0].Leg[j].Destination[0].$.time;
    }
msg.payload.type = 'message'
    msg.payload.chatId = msg.originalMessage.from.id;
    msg.payload.content = output

return msg;
//node.send(msg);
}

With node.send (msg); I get one message per trip.
Unfortunately asynchronous.
With "return msg" I get only the first message of the array. The loop then seems to end. How do I get the complete array synchronized?

0 Likes

#2

Here is a link for sending multiple messages:
https://nodered.org/docs/writing-functions#multiple-messages

0 Likes

#3

I don't understand what you mean by synchronized, using node.send() it should send one message each time it goes round the loop. If that is not what you want then what do you want?

0 Likes

#5

I found the mistake. you're right

0 Likes

#6

Whenever I see "looping" through data sets, I think about using either a change node with a JSONata expression, or a template node with mustache-style iteration and substitution...

If you don't mind posting the incoming msg.payload as a JSON string, I can give you a couple other solutions, at least for future reference.

0 Likes

#7

hier you find the incoming msg as Json String

https://wetransfer.com/downloads/45bdb553236c84b75170f7940fccfac520180719201707/aceeeced6d3c0c4f93ab8f8ff445e0f220180719201707/c20539

0 Likes