Home > other >  Looping over values in an object array - nodeJS
Looping over values in an object array - nodeJS

Time:10-11

I'm having trouble looping over all objects in my object array. I can loop over the first object but it does not move onto the next one in my for loop.

var results = [
 { company: 'eureka_jp', companyurl: 'hackerone.com/eureka_jp' },
 { company: 'evernote', companyurl: 'hackerone.com/evernote' },
 { company: 'exodus', companyurl: 'hackerone.com/exodus' },
],

This is my code that initialises the loop. The main aim of this code is to loop over each company url value and perform a web scrape identified by the page.screenshot function.

The console.log(urlLoop) returns only the first value of the companyurl property of the object.

  for (const value of Object.values(results)) {
  
  let urlLoop = `${value.companyurl}` 



  for (let i = 0; i < urlLoop.length; i  ) {
  const browser = await puppeteer.launch({ headless: false })
  const page = await browser.newPage()
  await page.goto("https://"   urlLoop)
  await new Promise(resolve => setTimeout(resolve, 10000));
  await page.screenshot({                     

    path: "./screenshot.png",                  
 
    fullPage: true                              
 
  }) 

  console.log ("New Page");

  }

CodePudding user response:

for (const value of Object.values(results)) this line gets an array containing values of the result objects. So you're looping through the for of loop.

Again you're looping through for loop (the nested one with urlLoop length) which causes the problem.

I think this is what you're trying to do.

for (const value of Object.values(results)) {
  
  let urlLoop = `${value.companyurl}` 

  // remove the for loop
  
  const browser = await puppeteer.launch({ headless: false })
  const page = await browser.newPage()
  await page.goto("https://"   urlLoop)
  await new Promise(resolve => setTimeout(resolve, 10000));
  await page.screenshot({                     

    path: "./screenshot.png",                  
 
    fullPage: true                              
 
  }) 
  console.log ("New Page");
}
  • Related