Search code examples
javascriptjsdocgoogle-custom-search

trouble reading result of google customer search results object in javascript


Does anyone know the syntax to use when reading a Google custom search results object?

Here is the JSDoc notation of the results object from https://developers.google.com/custom-search/docs/element:

{
  content: string,
  contentNoFormatting: string,
  contextUrl: string, // For image search results only
  fileFormat: string,
  image: { // For image search reseults only
    height: number,
    url: string,
    width: number,
  },
  perResultLabels: !Array<{
    anchor: string,
    label: string,
    labelWithOp: string,
  }>,
  richSnippet: !Array<!Object>, // For web search results only
  thumbnailImage: {
    height: number,
    url: string,
    width: number,
  },
  title: string,
  titleNoFormatting: string,
  url: string,
  visibleUrl: string,
} 

I need to get at the "url" (thumbnailimage.url) but unsure of the syntax to use to reference it.

here is where I need to use it. See comment below

here is where I need to use it.  See comment below

const makeResultParts = (result) => {
const anchor = document.createElement('a');
anchor.href = result['thumbnailImage'] //  <<---this needs to be the thumbnailImage.url but that syntax does not work
anchor.target = '_blank';
anchor.classList.add('gs_title');
anchor.appendChild(document.createTextNode(result['visibleUrl']));
const span = document.createElement('span');
span.innerHTML = ' ' + result['title'];
return [anchor, span];
};

Solution

  • Assuming result['thumbnailImage'] always exists (according to the docs it should for image searches), this should work for you:

    const makeResultParts = (result) => {
      const anchor = document.createElement('a');
      anchor.href = result['thumbnailImage']['url'] //  <<--- Access the url attribute of the thumbnailImage entry
      anchor.target = '_blank';
      anchor.classList.add('gs_title');
      anchor.appendChild(document.createTextNode(result['visibleUrl']));
      const span = document.createElement('span');
      span.innerHTML = ' ' + result['title'];
      return [anchor, span];
    };