googleplex
googleplex

Reputation: 1

Displaying local storage data in a table

So I currently have this stored in my localStorage:

{cart: "[{"Author":"Micheal Grant","title":"Gone"},{{"Author":"Micheal 
Grant","title":"Fear"}]"

I was just wondering how I would go about retrieving this data and displaying it in a table:

For example:

<table border="1">
  <tbody>
    <tr>
      <th> Book Title </th>
      <th> Author </th>
    </tr>
    <tr>
      <td class="Book_Title">Gone </td>
      <td class="Author">Micheal Grant</td>
    </tr>
    <tr>
      <td class="Book_Title">The Knife of never letting go</td>
      <td class="Author">Ryan Howard</td>

    </tr>
 </tbody>
</table>

Upvotes: 0

Views: 8757

Answers (3)

Mamun
Mamun

Reputation: 68933

Once you retrieve item from localStorage like localStorage.getItem(dataObj);, you can use jQuery's each() to loop through all the items. Inside the handler function to create the tr with the values and append that to tbody.

Please notice the use of Template literals inside append().

Try the following way:

//localStorage.getItem(dataObj);
var jsonData = {cart: [{"Author":"Micheal Grant","title":"Gone"},{"Author":"Micheal Grant","title":"Fear"}]};

$.each(jsonData.cart, function(key, value){
  $('tbody').append(`<tr>
  <td class="Book_Title">${value.title}</td>
  <td class="Author">${value.Author}</td>
</tr>`);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border="1">
  <tbody>
    <tr>
      <th> Book Title </th>
      <th> Author </th>
    </tr>
  </tbody>
</table>

Upvotes: 0

Anurag Singh Bisht
Anurag Singh Bisht

Reputation: 2753

You can retrieve the data from localStorage using localStorage.getItem function.

Once you have the data, iterate through the cart attribute, and use javascript template strings to create the html structure. Advantage of using template strings is that it's more readable and you can easily insert javascript variables inside them using ${}.

//localStorage.getItem(dataObj);
var data = {
  cart: [{
    "Author": "Micheal Grant",
    "title": "Gone"
  }, {
    "Author": "Micheal Grant",
    "title": "Fear"
  }]
};

var tableData = data.cart.map(book => (
  `
    <tr>
      <td>${book.title}</td>
      <td>${book.Author}</td>
    </tr>
  `
)).join('');

var tbody = document.querySelector('#body');
tbody.innerHTML = tableData;
<table border="1">
  <thead>
    <tr>
      <th> Book Title </th>
      <th> Author </th>
    </tr>
  </thead>
  <tbody id="body">
  </tbody>
</table>

Upvotes: 0

Vicky charanpahari
Vicky charanpahari

Reputation: 97

Ok so here is what you should do

var cart= JSON.parse( localStorage.getItem('cart' ) );
    $.each(cart, function(key, value){
      $('tbody').append(`<tr>
      <td class="Book_Title">${cart.title}</td>
      <td class="Author">${cart.Author}</td>
    </tr>`)
})

Upvotes: 1

Related Questions