Ask your JavaScript questions! Pay money and get answers fast! Comodo Trusted Site Seal
Official PayPal Seal

maintain localstorage appending a few names each week. JavaScript


I want to maintain an ever-growing localStorage named 'eligible'. Just a unique few names will be added each week.
The object fields in 'eligible' are 'name' and 'date'. I check if the record exists (matches date and name).

function eligible(){ yyyymmdd(); // today's date YYYY-MM-DD
old_data = JSON.parse(localStorage.getItem('eligible'));

for (i = 1; i <= 64; i++) {

// get player name from form
let temp_1 = document.getElementById("P" +i).value;

//check for existing record
found = false; for (x = 0; x < old_data.length; x++) //ERROR

{if ((old_data[x].name == temp_1) && (old_data[x].date == today)) {
found = true; break;}}

// if not found add the record to the 'old_data' object array
if ((temp_1 > "") && !(found)) {old_data.push({ name: temp_1, date: today});}


localStorage.setItem("eligible", JSON.stringify(old_data));

Answers (1)


Rainner Lins answers:

The first time you try to get something from the store it will be null since there's nothing there, you need to check for that and default to an empty array.

You can also use Array.filter() to check if there is something in an array without having to use a for loop, it's much cleaner, try something like this: