I’m building an expense tracker app that saves data entered into a form, then registered into a table under(Name, Date and Amount) inputs, it then saves that data in the browser’s local storage as an array. I am trying to retrieve the table data as it was registered into the table(in the correct rows and columns) when the page is reloaded.
//FUNCTION TO GET EXISTING EXPENSES FROM LOCAL STORAGE WHEN PAGE IS REFRESHED (display Table on the screen with refreshing Page)
function getExpenses(expenses) {
//CHECK If an expense exists in Local Storage
//Checks if expense exists
if (localStorage.getItem("expenses") === null) {
expenses = []; //create a new array for expenses if none exists
} else {
expenses = JSON.parse(localStorage.getItem("expenses")); //Gets back the array of existing expenses if expenses exist
}
expenses.forEach((item) => {
//create <tr></tr>
const tableRow = document.createElement("tr"); //new table row
tableRow.classList.add("table-row"); //set class to t-row
tableHead.appendChild(tableRow); //Append new row(.tableHead) to the table in HTML
//create <td></td>
const tableDataA = document.createElement("td"); //New Table Data Element
tableDataA.innerText = item;
tableRow.appendChild(tableDataA);
const tableDataB = document.createElement("td");
tableDataB.innerText = item;
tableRow.appendChild(tableDataB);
const tableDataC = document.createElement("td");
tableDataC.innerText = item;
tableRow.appendChild(tableDataC);
//APPEND
expenseTable.appendChild(tableRow); //To Append .t-row to the Table element in our HTML file
});
}
>Solution :
Based on the output you’re getting, expenses is an array of strings rather than an array of objects. So you need to iterate over it in groups of 3, putting sequential elements from each group into a different TD.
You can’t do this easily with forEach(), so use a for loop.
for (let i = 0; i < expenses.length; i += 3) {
//create <tr></tr>
const tableRow = document.createElement("tr"); //new table row
tableRow.classList.add("table-row"); //set class to t-row
tableHead.appendChild(tableRow); //Append new row(.tableHead) to the table in HTML
//create <td></td>
const tableDataA = document.createElement("td"); //New Table Data Element
tableDataA.innerText = expenses[i];
tableRow.appendChild(tableDataA);
const tableDataB = document.createElement("td");
tableDataB.innerText = expenses[i + 1];
tableRow.appendChild(tableDataB);
const tableDataC = document.createElement("td");
tableDataC.innerText = expenses[i + 2];
tableRow.appendChild(tableDataC);
//APPEND
expenseTable.appendChild(tableRow); //To Append .t-row to the Table element in our HTML file
}
It would probably be better if you redesigned your expenses array to be an array of objects rather than separate elements for each column, e.g.
[
{
name: "Gym",
date: "2022-02-15",
amount: 200
},
{
name: "Grocery",
date: "2022-02-20",
amount: 500
}
]
