javascriptnode.jsweb-scrapingcheerio

cheeriojs - How to loop through every object?


I have this code below:

$('.name').filter(function(){
    var data = $(this);
    name = data.text();

    json.name = name;
})

This will return the text from this div:

<a href="javascript:void(0)" class="name">This is a name</a>

Basically on the page there around 20 photos of people, so there are around 20 or so <a> tags on the page with a class name of name. How would I loop through each <a> tag and produce a JSON variable which would contain something like this below

{ [id: 0, name: 'name 1'],[id: 1, name: 'name 2'] }

At the moment I can only get it to hold the value of one name, which is useless to me at the moment!

Any help appreciated!


Solution

  • It seems you have jQuery available, that eases the task a little bit. Using .each():

    var myList = [];
    var id = 0;
    $('name').each(function() {
      var name = $(this).text();
      myList.push({id: id, name: name});
      id = id + 1;
    }
    console.log(myList);