Skip to content

Support for...of and entries iteration? #1191

@papandreou

Description

@papandreou

Hi!

I wanted to do some quick scraping and found $(...).each(() => {...}) a bit uncomfortable now that we have for ... of in ES6. Basically I'd like to do the following:

const cheerio = require('cheerio');
const $ = cheerio.load(myHtml);
for (const element of $('.someClass')) {
  // ...
}

for (const [index, element] of $('.someOtherClass').entries()) {
  // ...
}

I whipped up a quick patch that allows the above syntax:

const cheerio = require('cheerio');

cheerio.prototype[Symbol.iterator] = function* () {
  for (let i = 0; i < this.length; i += 1) {
    yield this[i];
  }
};

cheerio.prototype.entries = function* () {
  for (let i = 0; i < this.length; i += 1) {
    yield [i, this[i]];
  }
};

LMK if this is out of scope -- if not I'll whip up a PR.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions