Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better to store array in localstorage or many variables?

Take for example a case where I have thousands of students.

So I'd have an array of objects.

students = [

{ "name":"mickey", "id","1" },
{ "name":"donald", "id","2" }
{ "name":"goofy", "id","3" }
...

];

The way I currently save this into my localstorage is:

localStorage.setItem('students', JSON.stringify(students));

And the way I retrieve this from the localstorage is:

var data = localStorage.getItem('students');
students = JSON.parse(data);    

Now, whenever I make a change to a single student, I must save ALL the students to the localStorage.

students[0].name = "newname";
localStorage.setItem('students', JSON.stringify(students));

I was wondering if it'd be better instead of keeping an array, to maybe have thousands of variables

localStorage.setItem('student1', JSON.stringify(students[0]));
localStorage.setItem('student2', JSON.stringify(students[1]));
localStorage.setItem('student3', JSON.stringify(students[2]));
...

That way a student can get saved individually without saving the rest?

I'll potentially have many "students".. Thousands. So which way is better, array or many variables inside the localstorage?

Note: I know I should probably be using IndexedDB, but I need to use LocalStorage for now. Thanks

like image 712
Shai UI Avatar asked Jan 06 '13 17:01

Shai UI


People also ask

How big can localStorage be?

LocalStorage should be avoided because it is synchronous and will block the main thread. It is limited to about 5MB and can contain only strings. LocalStorage is not accessible from web workers or service workers.

Is it good to store in local storage?

Local storage provides at least 5MB of data storage across all major web browsers, which is a heck of a lot more than the 4KB (maximum size) that you can store in a cookie. This makes local storage particularly useful if you want to cache some application data in the browser for later usage.

How will you store arrays and lists in local storage?

Use localStorage. setObj(key, value) to save an array or object and localStorage. getObj(key) to retrieve it. The same methods work with the sessionStorage object.

Can I store an array in localStorage?

Save Array In localStorageYou can save the array by using the setItem method. const myBlogs = ["https://catalins.tech", "https://exampleblog.com"]; localStorage. setItem('links', JSON.


1 Answers

For your particular case it would probably be easier to store the students in one localStorage key and using JSON parse to reconstruct your object, add to it, then stringifying it again and it would be easier than splitting it up by each student to different keys.

If you don't have so many data layers that you really need a real local database like IndexedDB, a single key and a JSON string value is probably OK for your case.

like image 137
sajawikio Avatar answered Sep 22 '22 16:09

sajawikio