Get text of multiple elements as separate values

I'm trying to collect info from WEB, but if there is 2 elements in one page, info stored in same obj line. How to store info in different line? code:

if (!error && response.statusCode == 200) {
  var $ = cheerio.load(html);
  $('#ctl00_MainContent_ipcAvaDay_upnlResultOutbound').each((e, el) => {
    var arrival_airport = $(el).find('.rowinfo2 td:nth-child(2)').text();
    var alio = [arrival_airport];

and the console.log im getting is

[RigaRiga] 

instead of

[Riga]
[Riga]

maybe some ideas ?

Upvotes: 1

Views: 1287

Answers (2)

pguardiario
pguardiario

Reputation: 54984

Just for clarity, avoiding this can be done in pre-ES6 as well as ES6 + arrow functions:

Pre-ES6 (no this):

var airports = $(el).find('.rowinfo2 td:nth-child(2)').map(function(i, el) {
  return $(el).text();
}).get();

ES6:

let airports = $(el).find('.rowinfo2 td:nth-child(2)').map((i, el) => $(el).text()).get()

Don't use this in these blocks because it's weird and it causes confusion.

Upvotes: 1

Rory McCrossan
Rory McCrossan

Reputation: 337610

When text() is called on a collection of elements jQuery will concatenate all the values in to a single string.

If you want to create an array of all the separate values, use map():

var arrival_airport = $(el).find('.rowinfo2 td:nth-child(2)').map(function() {
  return $(this).text();
}).get();
console.log(arrival_airport);

Upvotes: 2

Related Questions