Can I force cheerio to return an array?

I’m using cheerio and axios to do some web scraping. Right now, I’m trying to select $(".color-data"), which should return three elements. However, it outputs a large, messy object, and if I use .toArray(), I get an error.

Any ideas on what to do? Here’s my code:

//import our packages
const axios = require("axios")
const cheerio = require("cheerio")
const data = []

//load html-color-names
axios.get("http://www.html-color-names.com/darkorchid.php")
    .then(html => {
      //console.log(html.data)
    const $ = cheerio.load(html.data)
    var arr = $(".color-data")
    console.log(arr) //returns object, arr.toArray() is a no go, arr.text() returns string
})

Update: I’ve tried https://teamtreehouse.com/community/returning-an-array-from-a-class-in-jquery - they suggest using each and pushing it to an array, but it doesn’t work. Any other ideas?

Update 2: If i use .text(), I get:

       DarkOrchid

        #9932cc

            rgb(153, 50, 204)

There’s too much whitespace to efficiently split this. I tried .html(), and I just get


        DarkOrchid

.data() returns an empty object {}.
More whitespace, again. Any ideas?

I solved it!

arr.each(function(i, elem) {
  a[i] = $(this).text();
});

Turns out, arrow expressions don’t work in Cheerio, I don’t know why.

1 Like

i tried this and it worked $(‘selector’).get().map((e=> ({
cont string :string= $(e).find(‘selector)’
}))

That’s impressive, because that isn’t valid JS, so I very much doubt that you tried it, let alone that it worked. Especially on a five year old question that already had an answer.

3 Likes