0

I'm doing some webscraping using puppeteer and node.js. I'm looping through data and I want to store the data dynamically to a variable depending on what I'm scraping during the loop. I'm then storing this data into a MySQL database.

Here is a sample of the code:

const subQ1
const subQ1A

const subQ2
const subQ2A

const subQ3
const subQ3A

for(var i = 1; i < 4; i++){
    
    | this is where the number of the loop should go (i), same thing below
    v
subQi = await page.evaluate((i) => {
            var linkGet = document.querySelector(`body > div.page-content.container > div:nth-child(${i}) > div.question_part_label`).innerHTML
         return linkGet;         
        },i);

subQ(i)A = await page.evaluate((i) => {
            var linkGet = document.querySelector(`body > div.page-content.container > div:nth-child(${i}) > div.question_part_label`).innerHTML
         return linkGet;         
        },i);
}

I know this might not be the practical way of doing things but I'm a bit of a noob. I've seen eval() as an option but everyone seems to suggest not using it and I'm wondering if theres another way of doing this. Thanks :)

ikito999
  • 11
  • 3
  • 1
    You would not do it the way you're trying to. Either create an array of variables and then you can access the array dynamically. Or, create an object with `.subQ1` and `.subQ1A` properties on it and then you can dynamically create the property name and access it as in `obj["subQ" + num + letter]`. – jfriend00 Nov 20 '20 at 01:57
  • Yah... basically: `var variables = []; for loop {variables.push(() => { return some stuff})}` – Shmack Nov 20 '20 at 04:03
  • Also, you cannot assign a value to a `const` variable *after* the declaration. – vsemozhebuty Nov 20 '20 at 06:20

0 Answers0