Skip to content
Advertisement

Iterate through array and call data function from loop

The follow should return 3 different results depending on the array value as it iterates through.

I think this question is correct, how can I change it so data{} is a function called from my loop and so a new set of data is posted each time? (difference is the array value) I’m not sure how I would do this so that the value matches and changes accordingly.

I have a switch included because my API doesn’t like the format of the input so have to change it.

Not even sure this is the best approach so any advice is helpful.

Input

"ABC, DEF, GHI"

Expected output

Call 1 Data =   {"result":{"u_department":"A B.C","record":"001"}}
Call 2 Data =   {"result":{"u_department":"D E.F","record":"002"}}
Call 3 Data =   {"result":{"u_department":"G H.I","record":"003"}}

Script

var tens = "ABC, DEF, GHI"
console.log(tens);
var letters = tens.split(',').map(string => string.trim());
console.log(letters);
// **** Add function? **** //
//Start Data
var data = {};
//Switch site to change format
var site = {};
switch (letters[0]) {
    case 'ABC':
        site = "A B.C";
        break;

    case 'DEF':
        site = "D E.F";
        break;

    case 'GHI':
        site = "G H.I";
        break;
}
var u_department = site;
data.u_department = u_department;
console.log(u_department)
//End Data
// *********************** //

//Request options
var options = {
    // POST Call, headers etc
    ...
    }
};
//Request function
function sendData(data) {
    var req = http.request(options, function(res) {
        console.log('STATUS: ' + res.statusCode);
        console.log('HEADERS: ' + JSON.stringify(res.headers));
    });
    req.write(data);
}
//Try send for each array item:
for (var i = 0; i < letters.length; i++) {
    sendData(data);
}

Advertisement

Answer

use a forEach loop in place of your for loop.

letters.forEach(letter => {
  var site;
  var data = {};
  switch (letter) {
    case 'ABC':
      site = "A B.C";
      break;
    case 'DEF':
      site = "D E.F";
      break;
    case 'GHI':
      site = "G H.I";
      break;
  }
  data.u_department = site;
  var options = {
    // POST Call, headers etc
  }
  sendData(data, options);
});

function sendData(data, options) {
    var req = http.request(options, function(res) {
        console.log('STATUS: ' + res.statusCode);
        console.log('HEADERS: ' + JSON.stringify(res.headers));
    });
    req.write(data);
}

You need to make options a parameter to sendData rather than accessing it as a global variable, since it’s local to the forEach loop.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement