Tripp
Tripp

Reputation: 67

Uncaught TypeError: Cannot read property 'map' of undefined on AJAX object

Is there a way that I can pass in N/A as default if there is no results? I want to be able to define it as "N/A" if the mapped object is empty on Title.

Some of the items under Media_x0020_Specialist_x0028_s_x.results return, but then some items are not returning and I'm getting that error.

Code:

  $.ajax({
    url: requestUri,
    type: "GET",
    dataType: "json",
    cache: false,
    headers: {
      accept: "application/json; odata=verbose"
    },
    success: function success(data) {
      onSuccess(data);
      ExportTable();
    }
  });

  function onSuccess(data) {
    var item = data.d.results;
    for (var i = 0; i < item.length; i++) {
      tableContent += "<tr>";
      tableContent +=
        "<td>" +
        item[i].Franchises_x0020_with_x0020_Shar.results
          .map(function(r) {
            return r.Title;
          })
          .join("; ") +
        "</td>";
      tableContent +=
        "<td>" + item[i].Stand_x0020_Alone_x0020_Franchis + "</td>";
      tableContent +=
        "<td>" +
        item[i].Franchise_x0020_Liason.results
          .map(function(r) {
            return r.Title;
          })
          .join("; ") +
        "</td>";


      tableContent +=
        "<td>" +
        item[i].Media_x0020_Specialist_x0028_s_x.results
          .map(function(r) {
            return r.Title;
          })
          .join("; ") +
        "</td>";

      tableContent += "</tr>";
      tableContent += "</tbody></thead>";
    }
    $("#title").append(tableContent);
  }

Here is the error: enter image description here

Upvotes: 1

Views: 130

Answers (2)

Dylan Kerler
Dylan Kerler

Reputation: 2187

You can use a ternary operator and repeat this for each item:

(item[i].Franchises_x0020_with_x0020_Shar.results ?          
   item[i].Franchises_x0020_with_x0020_Shar.results
      .map(function(r) {
          return r.Title;
      })
      .join("; ")
:
   "N/A")

Personally, I would wrap it in parenthesis to make it clearer what is going on (like above).

Alternatively, with the newer javascript features you can use optional chaining which was created to address this very problem:

   item[i].Franchises_x0020_with_x0020_Shar?.results
          .map(({ Title }) => Title))
          .join("; ") 
   || "N/A"

Upvotes: 1

simmer
simmer

Reputation: 2711

Further advice: you've got a lot of repeated code there, and concatenating strings in javascript using + is not as readable as doing so with template literals.

Here's a solution that's more concise, readable, and can be repeated for other data you might have:

$.ajax({
  url: requestUri,
  type: "GET",
  dataType: "json",
  cache: false,
  headers: {
    accept: "application/json; odata=verbose"
  },
  success: function success(data) {
    onSuccess(data);
    ExportTable();
  }
});


// we'll reuse this function each time we want to get a semicolon-separated list of titles
function getFranchiseTitles(franchises) {
  var noResultsMessage = 'N/A';

  // is "results" present on this object? does it have length?
  var hasResults = !!franchises.results && !!franchises.results.length;

  // only attempt map if there are results to map over
  return hasResults
    ? franchises.results.map(f => f.Title).join('; ')
    : noResultsMessage;
}


function onSuccess(data) {
  var results = data.d.results;

  // map over results, instead of using a for loop
  var tableRows = results.map(result => {

    // destructure & rename each result to get child results
    var {
      Franchises_x0020_with_x0020_Shar: shared,
      Stand_x0020_Alone_x0020_Franchis: standalone,
      Franchise_x0020_Liason: liason,
      Media_x0020_Specialist_x0028_s_x: specialist
    } = result;

    // get our titles from child objects
    var sharedTitles = getFranchiseTitles(shared);
    var standaloneTitles = getFranchiseTitles(standalone);
    var liasonTitles = getFranchiseTitles(liason);
    var specialistTitles = getFranchiseTitles(specialist);

    // return markup for this table row with titles inserted
    return `<tr>
      <td>${sharedTitles}</td>
      <td>${standaloneTitles}</td>
      <td>${liasonTitles}</td>
      <td>${specialistTitles}</td>
    </tr>`
  }).join('');

  // wrap with outer table tags
  var tableContent = `<table><tbody>${tableRows}</tbody></table>`;

  // insert into element
  $("#title").append(tableContent);
}

Upvotes: 0

Related Questions