Search code examples
javascriptnode.jsgoogle-chrome-devtoolspuppeteerheadless-browser

Passing arguments into map()


I am trying to use the built in map() function on an Array.from () that returns some elements using Puppeteer.

The below is the code:

let res = await page.evaluate(elementPath => {
  return Array.from(document.querySelectorAll(elementPath), (cin, index) => {
    return {
      cs: `state is ${this.s}`, // returns state is undefined
      cinemaIndex: index,
      cinemaId: cin.getAttribute('data-id'),
      cinemaName: cin.getAttribute('data-name'),
      cinemaURL: cin.getAttribute('data-url'),
    };
  }, {
    s: 'NSW'
  });
}, `div[data-state=${cinemaState}] div.top-select-option a.eccheckbox`, cinemaState);

I am not able to assign cs with variable s or cinemaState.

Wondering if you have solution


Solution

  • I am able to explain this. this is what has worked for me. I had to replace the arrow function to a traditional function

    let res = await page.evaluate(elementPath => {
      return Array.from(document.querySelectorAll(elementPath), function (cin, index) // changed from (cin, index) => 
    {
        return {
          cs: `state is ${this.s}`, // returns state is undefined
          cinemaIndex: index,
          cinemaId: cin.getAttribute('data-id'),
          cinemaName: cin.getAttribute('data-name'),
          cinemaURL: cin.getAttribute('data-url'),
        };
      }, {
        s: 'NSW'
      });
    }, `div[data-state=${cinemaState}] div.top-select-option a.eccheckbox`, cinemaState);