Better to store array in localstorage or many variables? - javascript

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

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.

There is limitation for the size of local storage and older browsers won't support it.
It is better to store in an array for couple reasons:
Can use loops to process them
No JSON needed
Always growable

Related

Best practice to retrieve specified data from mongoDB

I have a collection with this fixed structure:
By fixed structure I mean I just push Objects to the level arrays which are starter - intermediate and advanced as you see.
Now suppose you want to fetch intermediate array only, I can do it like this and it works fine:
const level = 'intermediate';
const motherModel = await db.Mother.findOne({});
const motherLevel = motherModel.cards[level]; // here we can get the specified level
This approach I need to retrieve all the data from database and save it to memory which may not be the best practice nor the fastest way because we only want to get the intermediate level right?
Is there any better ways to do this? or I'm totally wrong and I can be fine with this approach?

Better design for data stored using HTML5 localStorage

I have a scenario on my web application and I would like suggestions on how I could better design it.
I have to steps on my application: Collection and Analysis.
When there is a collection happening, the user needs to keep informed that this collection is going on, and the same with the analysis. The system also shows the 10 last collection and analysis performed by the user.
When the user is interacting with the system, the collections and analysis in progress (and, therefore, the last collections/analysis) keep changing very frequently. So, after considering different ways of storing these informations in order to display them properly, as they are so dynamic, I chose to use HTML5's localStorage, and I am doing everything with JavaScript.
Here is how they are stored:
Collection in Progress: (set by a function called addItem that receives ITEMNAME)
Key: c_ITEMNAME_Storage
Value: c_ITEMNAME
Collection Finished or Error: (set by a function called editItem that also receives ITEMNAME and changes the value of the corresponding key)
Key: c_ITEMNAME_Storage
Value: c_Finished_ITEMNAME or c_Error_ITEMNAME
Collection in the 10 last Collections (set by a function called addItemLastCollections that receives ITEMNAME and prepares the key with the current date and time)
Key: ORDERNUMBER_c_ITEMNAME_DATE_TIME
Value: c_ITEMNAME
Note: The order number is from 0 to 9, and when each collection finishes, it receives the number 0. At the same time, the number 9 is deleted when the addItemLastCollections function is called.
For the analysis is pretty much the same, the only thing that changes is that the "c" becomes an "a".
Anyway, I guess you understood the idea, but if anything is unclear, let me know.
What I want is opinions and suggestions of other approaches, as I am considering this inefficient and impractical, even though it is working fine. I want something easily maintained. I think that sticking with localStorage is probably the best, but not this way. I am not very familiar with the use of Design Patterns in JavaScript, although I use some of them very frequently in Java. If anyone can give me a hand with that, it would be good.
EDIT:
It is a bit hard even for me to explain exactly why I feel it is inefficient. I guess the main reason is because for each case (Progress, Finished, Error, Last Collections) I have to call a method and modify the String (adding underline and more information), and for me to access any data (let's say, the name or the date) of each one of them I need to test to see which case is it and then keep using split( _ ). I know this is not very straightforward but I guess that this whole approach could be better designed. As I am working alone on this part of the software, I don't have anyone that I can discuss things with, so I thought here would be a good place to exchange ideas :)
Thanks in advance!
Not exactly sure what you are looking for. Generally I use localStorage just to store stringified versions of objects that fit my application. Rather than setting up all sorts of different keys for each variable within localStore, I just dump stringified versions of my object into one key in localStorage. That way the data is the same structure whether it comes from server as JSON or I pull it from local.
You can quickly save or retrieve deeply nested objects/arrays using JSON.stringify( object) and JSON.parse( 'string from store');
Example:
My App Object as sent from server as JSON( I realize this isn't proper quoted JSON)
var data={ foo: {bar:[1,2,3], baz:[4,5,6,7]},
foo2: {bar:[1,2,3], baz:[4,5,6,7]}
}
saveObjLocal( 'app_analysis', data);
function saveObjLocal( key, obj){
localStorage.set( key, JSON.stringify(obj)
}
function getlocalObj( key){
return JSON.parse( localStorage.get(key) );
}
var analysisObj= =getlocalObj('app_analysis');
alert( analysisObj.foo.bar[2])

Is there something similar to sessionStorage but with multidimensional keys?

I'd like to save off values of a tree-like structure locally, then retrieve them based on user interaction. After some research, I found that sessionStorage (or localStorage) might be a good way to go about doing this. But I'm having trouble saving nested data.
Normally you have:
sessionStorage['key'] = 'someString';
I tried to implement something like:
sessionStorage['key1'] = [];
sessionStorage['key1']['key2'] = 'someString';
but I got an undefined error.
I've checked out few other storage libraries, but they only offer that single key-value pair option. Is there anything I'm missing?
Use JSON to serialise the nested data into a string, then decode it when you need to access it as an object...
var nested = {some:{nested:'object'}}
var asJson = JSON.stringify(nested)
sessionStorage['data'] = asJson
var asObject = JSON.parse(sessionStorage['data'])
From developer.mozilla.com:
The DOM Storage mechanism is a means through which string key/value
pairs can be securely stored and later retrieved for use.
Hence I think you cannot store array/dictionary directly in session storage. I highly suggest you that check this link out:
https://developer.mozilla.org/en-US/docs/DOM/Storage

Can I have more than one localstorage instance?

I have some code to store cued Ajax requests in localstorage that works well with one key per request. I'm also storing other persistent data in the same place - I've separated this by using a unique key prefix so that this doesn't interfere with my Ajax cue.
I now have need to store yet further data and I think it's getting messy.
Is there some way of having multiple localstorage instances?
You can't have multiple localStorage instances, you can't instantiate it. You don't have to separate out every single bit of data with unique key prefix if they can be logically grouped together. As long as those data can be serialized you can do something like this:
var requests = {reqId2 : reqObj, reqId2 : reqObj};
localStorage.setItem("ajax_requests", JSON.stringify(requests));
// then when you want to add additional requests into localStorage
var requests = JSON.parse(localStorage.getItem("ajax_requests"));
requests[reqId] = reqObj;
Just remember to store all data that can be logically grouped together, it should help you with the organization.

Storing JS arrays and objects in a database

I have an application that lets users build things in JS. I want the user to be able to save the current state of his work to reuse it or share it, but what he has is a collection of JS objects stored in a JS array, with very different properties (color, label, x/y position, size, etc.).
SQL seems terrible for that particular task, forcing me to maintain tables for every different object, and alas I know very little about NoSQL database. What tools would you use to perform this ? MongoDB sounds promising but before I learn a whole new DB paradigm I want to be sure that I am heading in the right direction.
Object to string:
You can store your objects in the DB as a JSON string. Here's a simple example:
var foo = new Object();
foo.Name = "James";
foo.Gender = "Male";
//Result: {"Name":"James","Gender":"Male"}
var stringRepresentation = window.JSON.stringify(foo);
Here's a working fiddle.
String to object:
To convert your string back to an object, simply call window.JSON.parse():
var myObject = window.JSON.parse(stringRepresentation);
Here's a working fiddle.
If you have no interest in quering the objects for their various properties but only persist them to save state, you can serialize the entire array to JSON and store it in any db you like as one string.
What's on the server?
Most languages have mature JSON implementations that convert JavaScript objects to native types, which you can then easily store in a SQL database.

Categories