Home > other >  Looping over an array and outputting a template string/literals in Javascript/Nodejs
Looping over an array and outputting a template string/literals in Javascript/Nodejs

Time:11-26

I'm fairly new to Javascript, and I am just trying to loop over an array, append the value of the loop iteration to a template string, and print it via console.log in a nodejs terminal.

I've written the following code to make my array:

// Get LTLAs from file
var fs = require("fs");
var text = fs.readFileSync("./LTLAs.txt", 'utf8');
var LTLAs = text.split("\n");

This gives me an array, see snippet below:

'Barking and Dagenham\r'
'Babergh\r'
'Aylesbury Vale\r'
'Ashford\r'
'Ashfield\r'
'Arun\r'
'Amber Valley\r'
'Allerdale\r'
'Adur\r'

And then I loop over this array with:

for (let i = 0; i < LTLAs.length; i  )
{
    const endpoint = `https://api.coronavirus.data.gov.uk/v1/data?filters=areaType=ltla;areaName=${LTLAs[i]}&structure={"ltla":"areaName","date":"date","Rate":"newCasesBySpecimenDateRollingRate"}`;
    console.log(endpoint);
}

I expected this to give me a neat set of strings, where the only difference is where the areaName=${LTLAs[i]} changes for each loop iteration. Instead I get a set of incomplete strings, with only the last of the loop actually being correct, as seen below:

&structure={"ltla":"areaName","date":"date","Rate":"newCasesBySpecimenDateRollingRate"}Dagenham
&structure={"ltla":"areaName","date":"date","Rate":"newCasesBySpecimenDateRollingRate"}
&structure={"ltla":"areaName","date":"date","Rate":"newCasesBySpecimenDateRollingRate"}le
&structure={"ltla":"areaName","date":"date","Rate":"newCasesBySpecimenDateRollingRate"}
&structure={"ltla":"areaName","date":"date","Rate":"newCasesBySpecimenDateRollingRate"}
&structure={"ltla":"areaName","date":"date","Rate":"newCasesBySpecimenDateRollingRate"}
&structure={"ltla":"areaName","date":"date","Rate":"newCasesBySpecimenDateRollingRate"}
&structure={"ltla":"areaName","date":"date","Rate":"newCasesBySpecimenDateRollingRate"}
https://api.coronavirus.data.gov.uk/v1/data?filters=areaType=ltla;areaName=Adur&structure={"ltla":"areaName","date":"date","Rate":"newCasesBySpecimenDateRollingRate"}

Any assistance on getting all of the strings to follow the same pattern as the final string would be appreciated.

Thanks in advance

CodePudding user response:

You need to remove carriage return symbol ('\r') from your strings to get proper output in node js (some browsers may ignore it).

You can either iterate over array:

var LTLAs = text.split("\n").map(string => string.replace('\r', ''));

Or you can split with \r\n instead of \n:

var LTLAs = text.split("\r\n")
  • Related