Search code examples
javascriptjquerynode.jscheerio

Header value not used as object key


enter image description here

I'm working with node , puppeteer and cheerio, and I'd like to scrape the header and footer info of the table

I have the following :

const data = await page.content(); // get all page html
const $ = cheerio.load(data);

const head = $('#tblAcctBal > thead > tr');
const foot = $('#tblAcctBal > tfoot > tr');
const h = $(head).find('th');
const f = $(foot).find('th');
for (let i = 0; i < h.length; i++) {
  const hElement = $(h[i]).text();
  const fElement = $(f[i]).text();
  myArr.push({hElement: fElement });
}
  console.log(myArr);

enter image description here

I can confirm from stepping through the code that the appropriate header column and footer column text is in both hElement, fElement.

However, when I look at the output of the array I see:

0:
{hElement: ''}
1:
{hElement: ''}
2:
{hElement: ''}
3:
{hElement: ''}
4:
{hElement: ''}
5:
{hElement: '$0.00'}
6:
{hElement: '$0.00'}
7:
{hElement: '$0.00'}
8:
{hElement: '$0.00'}
9:
{hElement: '$0.00'}

In the loop, I see the correct header value , but hElement shows up in the array as the key for all the objects - what am I doing wrong?


Solution

  • This line:

     myArr.push({hElement: fElement });
    

    Needs to be this:

     myArr.push({[hElement]: fElement });