Search code examples
javascriptweb-scrapingcheerio

How do I add a new field for every object in the array?


How do I add a new shortText field to each object inside the articles array?

articles.forEach((article) => {
        request(article.link, (err, response, html) => {
          if (!err && response.statusCode == 200) {
            const $ = cheerio.load(html);
            const textData = $('.ssrcss-hmf8ql-BoldText');
            textData.each((index, element) => {
              article.shortText = $(element).text();
            });
          }
        });
      });

Example articles array

[
  {
    headline: 'Scale of Russian mercenary mission in Libya exposed',
    link: 'https://bbc.com/news/world-africa-58009514'
  },
  {
    headline: 'Afghan president rallies Taliban-besieged city',
    link: 'https://bbc.com/news/world-asia-58170847'
  }
]

I want to loop through the above arrray and add the shortText field to each object


Solution

  • //add fullname field in array of objects
    
    /*
    arrayOfObjects =arrayOfObjects.map((instanceObject) => ({
            ...instanceObject,
            newfield : values,
            }))
    */
    
    const getUsers = async () => {
      const response = await fetch(
        "https://www.json-generator.com/api/json/get/cfrfjgAOIy?indent=2"
      );
      let users = await response.json();
    
      users = users.map((person) => ({
        ...person,
        fullname: `${person.firstName} ${person.lastName}`,
      }));
    
      console.log(users);
    };
    
    getUsers();