user9371615
user9371615

Reputation: 67

how to iterate in cheerio using .each

I'm trying to scrape a page to pull in img src into an array. I'm using cheerio library.

Here is what I have:

$ = cheerio.load(body);
let flags = [];

$('figure').each(function(i, ele) {
  // get image and country name, website use 'figcaption' under 'figure'
  let imgTag = $(ele).children('img').attr('src');
  let countryName = $(ele).children('figcaption').text().trim();

  // create obj
  let obj = {
    img: imgTag,
    country: countryName
  }

  // add to object
  flags[i] = obj;
  console.log(flags);
});

My output looks like this:

[ { img:
     'https://cdn.staticaly.com/gh/hjnilsson/country-flags/master/svg/ad.svg',
    country: 'Andorra' } ]

I'm not getting any errors in the console. But what I'm looking for is ALL of the img src's. Its currently only grabbing the 1st one.

After researching I saw a github issue where someone tried using an arrow function but based on the cheerio docs you should be using regular functions.

Upvotes: 1

Views: 1839

Answers (1)

pguardiario
pguardiario

Reputation: 54984

You really want map:

let flags = $('figure').get().map(ele => {
  return {
    img: $(ele).find('img').attr('src'),
    country: $(ele).find('figcaption').text().trim()
  }
})
  • I'm using js map instead of cheerio map because I think it's simpler.

  • The cheerio docs don't use arrow functions because they were written pre-ES6. Feel free to use them.

Upvotes: 3

Related Questions