Home > Software design >  How to print out multiple responses not just the first line
How to print out multiple responses not just the first line

Time:10-06

  if(response){
            const temp = response[0];
            const recipient_id = temp["recipient_id"];
            const recipient_msg = temp["text"];      

I have this if statement where it only prints out the first response (response[0]), how would I print out multiple responses regardless of what amount not just the first line.

CodePudding user response:

You can use Array#forEach or a for ... of loop to iterate over the array.

for (const r of response) {
    console.log(r); // or extract individual properties to log
}

CodePudding user response:

Considering that the input is similar to the following:

const response = [
    {
        recipient_id: 1,
        text: "t1"
    },
    {
        recipient_id: 2,
        text: "t2"
    }
];

you can loop on the response array using forEach (as @Unmitigated mentioned) and print details like recipient_id or text of each element r:

if (response) {
    response.forEach((r) => {
        console.log(r.recipient_id, r.text);
    });
}

In this example, the output is the following:

1 't1'
2 't2'
  • Related