Storing JS arrays and objects in a database - javascript

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.

Related

How can a linq query be converted to JavaScript array containing only values?

I have a JavaScript grid library (it creates a table on the page) that accepts a JavaScript array as input, for rendering in the grid. I'm not certain, however, how to convert a Linq-to-SQL query (against a SQL Server database) to a JavaScript array containing only values.
I tried this, but it included the table column names in the JSON key (and I don't want JSON anyway, I want a JavaScript string array, unless this can be converted to an array?):
JsonConvert.SerializeObject(query)
Example of the format I need to produce:
[1,2,3],[4,5,6]
Environment: .NET Core 3.1
edit: Here is a sample of what I've currently got, this returns the less than desirable JSON (due to the query results being so large, having a JSON key for very element is going to literally double the size of the query):
Devices Table
ID Name
1 iPhone7
2 iPhone8
3 iPhone9
Needed Array (Note: no column names)
[1, "iPhone7"],[2, "iPhone8"],[3, "iPhone9"]
Current C# code in the controller method (returns undesirable key for every element currently)
var query = db.Devices;
var formattedResult = JsonConvert.SerializeObject(query);
return Ok(formattedResult);
Technically, you could do this:
var query = db.Devices.AsEnumerable()
.Select(d => new object[]{d.ID, d.Name});
var formattedResult = JsonConvert.SerializeObject(query);
return Ok(formattedResult);
But then the code on the other end of your request is going to have to translate all those arrays back into objects.
It's rarely worthwhile to complicate your model like this in order to optimize the size of your network traffic. If you're pulling enough items over the wire to make this a performance issue, you're likely to encounter a variety of other performance issues. I would first consider other options, like implementing paging.
Did you try
var query = db.Devices.ToList();
var array = JArray.FromObject(query);
return Ok(formattedResult)

Pass multidimensional javascript array between pages

I need to transfer a multi-dimensional JavaScript array to another page, without using any library. What I can use is JavaScript, PHP and other languages that doesn't need a library.
I have a three-dimensional array which is build like this:
storage[category][field][multiple answers] and has a lot of values.
I need to transfer it to another page so I can get all the values like:
alert(storage[5][4][8]);
=======================================================================
Well, I can pass a normal variable to another page but I cant get the values from my array when I'm testing: storage[1][1][1] for example.The big question is how I can pass a multidimensional array to another page and still be able to get the values like this: storage[1][1][1]
As I get it I'm forced to pass all the 121 arrays you can se below to be able to access all dimensions in the array.
My array is built up like this:
storage = new Array();
for (var i1=1;i1<12;i1++){
storage[i1] = new Array();
for (var i2=1;i2<12;i2++){
storage[i1][i2] = new Array();
}
}
Without using a library like jQuery, you can convert your array to JSON, pass it via a URL and decode it on the target page. Converting it to JSON would look like:
var json_string = JSON.stringify(your_array);
Then pass it in a URL:
var your_url = "http://www.your_website.com/page.html?json_string=" + json_string;
And you could decode it back to an array like so:
var your_new_array = JSON.parse(getUrlVars()["json_string"]);
For some more reading, check out this JSON page: http://www.json.org/js.html
JSON.stringify() is supported by all major browsers. Send it to the server via a POST, then have your php retrieve the variable from $_POST and send it back.
As far as I can see there are two main ways to do what you want:
Pass the array to the webserver, and have it send it back on next request.
Store the data locally in the browser.
The first way could get pretty complicated. You would have to store the data in a database, file or cookie/session.
The second way would be the easiest. Use javascript to store the array in the browser. You can either use a cookie, or use the localStorage object.
Using a cookie would require you to serialize the data manually. It would also get passed to the server, so if you want to save bandwidth, you would want to avoid this.
The localStorage method would only store the data locally, and you also don't need to serialize anything, the browser takes care of this for you.
See the links below for more examples.
http://www.w3schools.com/html/html5_webstorage.asp
http://www.w3schools.com/js/js_cookies.asp

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

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
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

HTML5 local storage sort

I am using local storage to store user entries and am displaying the entries on another page. I need a way to sort them based on the most recent date and time of edit. Is there a way to do this with HTML5. If not, what's the easiest/most effective way to do so?
Thanks for the inputs.
If your keys/values have an inherent order to them (alphabetical, numerical, etc), then putting a timestamp in them may be superfluous. Although the Storage object has no sort method, you can create a new Array() and then sort that.
function SortLocalStorage(){
if(localStorage.length > 0){
var localStorageArray = new Array();
for (i=0;i<localStorage.length;i++){
localStorageArray[i] = localStorage.key(i)+localStorage.getItem(localStorage.key(i));
}
}
var sortedArray = localStorageArray.sort();
return sortedArray;
}
The disadvantage to this is that the array is not associative, but that is by nature of the JavaScript Array object. The above function solves this by embedding the key name into the value. This way its still in there, and the functions you'd use to display the sorted array can do the footwork of separating the keys from the values.
You've got to pair the timestamp with the stored value somehow, you can create a wrapper object for each value and store the value and the timestamp in a single object. Assuming you have a value myvalue you want to store with reference myref:
var d=new Date();
var storageObject = {};
storageObject.value = myvalue;
storageObject.timestamp = d.getTime();
localStorage.setItem(myref, JSON.stringify(storageObject));
On the other page you then need to rehydrate your objects into an array and implement your compareFunction function.
Your other option would be to use Web SQL Database and Indexed Database API which lets you more naturally store and query this sort of multifaceted info, but you would probably have to create some sort of abstract wrapper to make things work easily cross browser.

Categories