简体   繁体   中英

Using json array to populate html table

I am using local storage to save an object. I am having troubles than using this object to populate a table. Right now the object is showing up as an array in the third column. How can I use the json array to fill column 1, column 2 and column 3 with the value, key and image from the object.

$(document).on('click', '[data-toggle=add]', function() {
    var latlng = $(this).data('latlng');
    var address = $(this).data('address');
    var image = $(this).data('image');
    var key = $(this).data('id');
    var testObject = {
      'latlng' : latlng,
      'address' : address,
      'image' : image
    };
    localStorage.setItem(key, JSON.stringify(testObject));
    updateTable();
});

function updateTable() {
    var tbody = document.getElementById("output");
    while(tbody.getElementsByTagName("tr").length > 0) {
       tbody.deleteRow(0);
    }
    var row;
    if(localStorage.length == 0) {
       row = tbody.insertRow(i);
       cell = row.insertCell(0);
       cell.colSpan = "4";
       cell.innerHTML = "Nothing to Show";
    }
    for(var i = 0; i < localStorage.length; ++i) {
        row = tbody.insertRow(i);
        cell = row.insertCell(0);
        cell.innerHTML = i;
        cell = row.insertCell(1);
        cell.innerHTML = localStorage.key(i)
        cell = row.insertCell(2);
        cell.innerHTML = localStorage.getItem(localStorage.key(i));
        cell = row.insertCell(3);
        cell.innerHTML = '<button class="btn btn-danger btn-sm" onclick="deleteItem(\'' + localStorage.key(i) + '\');"><i class="fa fa-trash-o"></i> Delete</button>';
    }
}

You haven't posted all your markup but I believe this is your problem:

You are not retreiving the localStorage correctly. You are saving a stringified version of a JSON object and then you are trying to access it directly as an object. Instead, you need to retrieve the localstorage item and parse it back to a JSON object, then iterate through it or access its properties as an object.

Replace:

cell.innerHTML = localStorage.key(i);

With:

json = JSON.parse(localStorage.key(i));

cell.innerHTML = json.latlng;// or json.address or json.image;

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM