skip to Main Content

The code below generates a table with the data retrieved from the AJAX call. Value "null" is presented across the table when a value isnt present in the JSON object. I would like to replace null with an empty string across the table.

$(function() {
    var requestUri = "SPO_SITE/_api/web/lists/GetByTitle('LIST_NAME')/items?$select=Title,Order0,Designation,Name,Landline,Mobile,email,Remarks,Department/ID,Department/Title&$expand=AttachmentFiles,Department&$filter=Department/Title%20eq%20%27"+filterTitle+"%27";
    $.ajax({
        url: requestUri,
        type: "GET",
        headers: {
            "accept": "application/json; odata=verbose"
        },
        success: onSuccess,
    });
    function onSuccess(data) {
        var objItems = data.d.results;
        var tableContent = '<table id="contactsTable"><thead class="thead-light"><tr><th>Designation</th><th>Name</th><th>Landline</th><th>Mobile</th><th>Email</th><th>Remarks</th></tr></thead>';
        for (var i = 0; i < objItems.length; i++) {
            tableContent += '<tr>';
            tableContent += '<td>' + objItems[i].Designation + '</td>';
            tableContent += '<td>' + objItems[i].Name + '</td>';
            tableContent += '<td>' + objItems[i].Landline + '</td>';
            tableContent += '<td>' + objItems[i].Mobile + '</td>';
            tableContent += '<td>' + objItems[i].email + '</td>';
            tableContent += '<td>' + objItems[i].Remarks + '</td>';         
            tableContent += '</tr>';
        }
        document.getElementById("contactsTable").innerHTML = (tableContent);
    }
});

2

Answers


  1. Assuming that the value in the properties is null and not 'null' then you can use falsy evaluation to coerce the value, like this:

    tableContent += '<td>' + (objItems[i].Designation || '') + '</td>';
    
    Login or Signup to reply.
  2. You could take a more comparct approach and add the mapped parts.

    const keys = 'Designation', 'Name', 'Landline', 'Mobile', 'email', 'Remarks'];
    
    tableContent += objItems
        .map(o => keys
            .map(k => `<td>${o[k] || ''}<td>`)
            .join('')
        )
        .map(s => `<tr>${s}<tr>`)
        .join('');
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search