Home > Net >  Data showing undefined in table
Data showing undefined in table

Time:05-15

I am trying to get my data into an HTML table. The JavaScript is properly detecting the data and is showing two rows in the table, which is correct. The issue is each of the fields of both rows display undefined. Not sure where to go from here.

$(function() {

  var records = [];
  $.getJSON('https://v1.nocodeapi.com/devmarq/airtable/RiBnzHulmTPHkgnD?tableName=JobListings&fields=company,logo,companyDescription,role,roleDescription,location,link,dateAdded&view=AllListings', function(data) {
    $.each(data.records, function parseJSON(i, f) {
      var tblRow = "<tr>"   "<td>"   f.company   "</td>"   "<td>"   f.companyDescription   "</td>"   "<td>"   f.role   "</td>"   "<td>"   f.roleDescription   "</td>"   "</tr>"
      $(tblRow).appendTo("#userdata tbody");
    });
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

<div >
  <div >
    <table id="userdata" border="2">
      <thead>
        <th>Company</th>
        <th>Company Description</th>
        <th>Role</th>
        <th>Role Description</th>
      </thead>
      <tbody>
      </tbody>
    </table>
  </div>
</div>

Again the table is showing two rows, which is correct, but each value of the rows says undefined.

CodePudding user response:

You need to pull the fields key out of the record object:

$(function() {
    var records = [];

    $.getJSON('https://v1.nocodeapi.com/devmarq/airtable/RiBnzHulmTPHkgnD?tableName=JobListings&fields=company,logo,companyDescription,role,roleDescription,location,link,dateAdded&view=AllListings', function(data) {
        $.each(data.records, function parseJSON(i, { fields: f }) {
            var tblRow = "<tr>"   "<td>"   f.company   "</td>"   "<td>"   f.companyDescription   "</td>"   "<td>"   f.role   "</td>"   "<td>"   f.roleDescription   "</td>"   "</tr>"
            $(tblRow).appendTo("#userdata tbody");
        });
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

<div >
  <div >
    <table id="userdata" border="2">
      <thead>
        <th>Company</th>
        <th>Company Description</th>
        <th>Role</th>
        <th>Role Description</th>
      </thead>
      <tbody>
      </tbody>
    </table>
  </div>
</div>

I changed the second argument of the parseJSON function from f to { fields: f }; this uses object destructuring to grab the value of the fields entry in the object passed to the second argument and assigns it to the f variable so that the rest of the code can use that object to get their values.

  • Related