Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getItem localstorage containing a string

I have multiple keys in my localstorage: task-1,task-2, task-3 ... I'm searching a way to get the total of the keys starting with the string "tasks-" in order to place it in my loop instead of localStorage.length.

In fact if I have an other app that uses the localstorage, my loop returns me a length corresponding to ALL the keys in the localStorage, including the ones that are out of the app in question.

   i=0;

   if(localStorage.getItem("task-"+i) != null){

     for( i = 0; i < localStorage.length; i++){ 

       console.log(i)

     }
  }

Thanks a lot for your help

like image 817
user1521149 Avatar asked Nov 13 '22 00:11

user1521149


1 Answers

If you control the creation of these items, it would make much more sense to store them in an object and use JSON to convert between object and string:

var tasksObject = {
    task1: ...,
    task2: ...,
    ...
};

window.localStorage.setItem('tasks', JSON.stringify(tasksObject));

... later ...

var tasks = JSON.parse(window.localStorage.getItem('tasks'));

for (var task in tasks) {
    // do stuff
}
like image 167
jbabey Avatar answered Dec 28 '22 00:12

jbabey