Search code examples
javascriptnode.jshttpsgethttp-post

How can I pass the values of two arrays to identifiers in a Javascript function?


I'm using the NodeJS npm-request library to make HTTPS GET requests to an API.

Instead of providing an individual First and Last name in by hand in every HTTP GET requests, I'm attempting to setup an array with a predefined list of names that will be cycled through and automate the process of making multiple HTTP GET Requests, however, I've hit an obstacle -- I can't seem to figure out how to pass the values from my firstNameArray and lastNameArray to the askQuestion function.

TL;DR how can I best reference and rotate 'i' position in two array variables firstNameArray and lastNameArray within my askQuestion function?

var firstNameArray = ["First", "First1", "First3"];
var lastNameArray = ["Last", "Last2", "Last3"];

function askQuestion (firstName, lastName) {
  var options = {
    method: 'GET',
    url: 'https://example.p.rapidapi.com/search/',
    qs: {first_name: **where firstNameArray[i] should go**, last_name: **where lastNameArray[i] should go**},
    headers: {
      'x-rapidapi-host': 'example.p.rapidapi.com',
      'x-rapidapi-key': 'key'
    }
  };
  request(options, function (error, response, body) {
    if (error) throw new Error(error);

    console.log(body); // print result
  });
}

Solution

  • You're probably not using the right data structure for this. If you have the ability to change the data structure, I would make an Array of Objects, so you get the correct data in every iteration of your loop.

    There's a few reasons for this, but you've run into one of them, which is that it's a pain to keep track of the index when you're just trying to cycle through the information.

    function askQuestion(user) {
      makeThatRequest(user.firstName, user.lastName);
    }
    
    const users = [{ firstName: 'First 1', lastName: 'Last 1' } /*, ...etc etc */ ];
    users.forEach(askQuestion)
    

    If you have to use that data structure, I would coerce it as soon as possible into the array of objects above by translating it

    const firstNames = ['First1', 'First2'];
    const lastNames = ['Last1', 'Last2'];
    
    const users = firstNames.map((firstName, index) => ({ firstName, lastName: lastNames[index] });
    
    // do the rest of the examples from the above
    

    Alternatively, if you don't want to do two passes over your user set you could...

    
    const firstNames = ['First1', 'First2'];
    const lastNames = ['Last1', 'Last2'];
    
    function askQuestion(firstName, lastName) {
       makeThatRequest(firstName, lastName)
    }
    
    for (let i = 0; i < firstNames.length; i++) {
      askQuestion(firstNames[i], lastNames[i]);
    }