Home > Software engineering >  How do I get the code to retrieve multiple search results (with a defined value I set) and populate
How do I get the code to retrieve multiple search results (with a defined value I set) and populate

Time:12-03

So this is the code

function getPerson( companyName,country,jobTitle) {

var key="AIzaSyAITL9pQFhBNT2NuL4xxurnuxusWfB3YB0"

let searchEngineId = "82e8012da8c2c4d0b"

let search = "site:linkedin.com/in intitle:" jobTitle " " country " " companyName

var options = { 'method' : 'get', 'contentType': 'application/json', }; response = UrlFetchApp.fetch("``https://www.googleapis.com/customsearch/v1?key=" key "&q=" search "&cx=``" searchEngineId, options);

let url = JSON.parse(response).items[0].formattedUrl let title = JSON.parse(response).items[0].title.split("-")[0]

var results = new Array(1); let info = new Array(2); info[0]=url info[1]=title results[0]=info

return results }

I'm still relatively new to code and haven't really tried much other than scouring the internet to try and find an answer.

CodePudding user response:

You want to loop over the items. You now accesing only the first item with items[0] i used the .forEach() method on the array and store the results in a predetermined array:

function getPerson(companyName, country, jobTitle) {

  var key = "AIzaSyAITL9pQFhBNT2NuL4xxurnuxusWfB3YB0"
  let searchEngineId = "82e8012da8c2c4d0b"
  let search = "site:linkedin.com/in intitle:"   jobTitle   " "   country   " "   companyName

  var options = {
    'method': 'get',
    'contentType': 'application/json',
  };
  
  const request = UrlFetchApp.fetch(`https://www.googleapis.com/customsearch/v1?key=${key}&q=${search}&cx=${searchEngineId}`, options);
  const data = JSON.parse(request.getContentText())
  const results = [];

  data.items.forEach(item => {
    const url = item.formattedUrl
    const title = item.title.split("-")[0]
    results.push([url, title])
  })
  
  return results
}
  • Related