Persist complex array in Javascript [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
Hello I am having a hard time understating what I need to do in order to persist a complex array I have. The array is filled through an ajax call to a jsonresult and has a couple of strings and 2 objects, something like this:
{
Name
Age
Surname
Object 1
Object 2
}
This array is filled whenever I load my "main page". Now when I change page to lets say page B I would like to still have access to those values.
I know that its possible to use json stringify but I would like to maintain the array without needing to convert it to a string, because I would need to convert the numbers back to numbers.
Any suggestions are greatly appreciated.

The key here is Now when I change page to lets say page B I would like to still have access to those values.
The Javascript scope (that is, all the variables and functions you want to use) only lives as long as the page does. So, if you refresh, it kills the scope (all your variables will disappear)!
So, how to persist your information? As the commenters have said, you've got some options.
Traditionally, cookies are used - there's a lot of tutorials on how to do that. They store a key, a value, and an expiration.
HTML5 API has introduced browser storage, which is generally better than cookies, but less widely supported (although it's pretty good now in 2015).
You can store it on the server using a server-side language like PHP, Ruby, Java, etc. and pass it back to the page when the page is rendered.
Basically, Javascript cannot store variables by itself if the page is refreshed. You've got to use one of the above options, which are each an interesting learning curve by themselves (outside the scope of this question).
I'd recommend, in order:
starting with session storage if you're just experimenting
cookies if you want to build a resilient solution
server-side stuff if you want to take the red pill.
Incidentally, your notation is not correct for Javascript - arrays are notated using
["foo", "bar", "etc"]
and Javascript objects (which can be used as associative arrays) look like
{ "key": "value", "ghandi": "india", "mandela", "south africa" }

Related

What would be the best solution to store and work with data in JavaScript without a database? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
Alright, please allow me to elaborate on that. I am trying to build a small application for visual flight planning, to help with the calculations. I am using HTML/CSS/Javascript to make something simple. There are objects for airports, waypoints and airplanes for example. You select an airport for your origin, another for your destination, input the waypoints you will fly through and choose the aircraft, and the app uses the coordinates and airplane characteristics to calculate the legs. It has a few more steps but that's the basic concept.
So what I would like to do is store the data in a separate file and retrieve just the data I need when the element is selected. I am a beginner level, so I don't know if I am day dreaming.
Right now what I did was create an array with all airports, another with all waypoints and another with the aircrafts. A function retrieves the data from the array and returns the object. But that seems like a waste of memory.
Another idea I had was to mae a function with a switch statement, using the ids (airport/waypoint code for example) and returning the object selected. I did this for the magnetic deviation, using the coordinates.
I would like to make something that I can update later in the future, but with a simple structure, if at all possible. SQL sure pops in mind, but I am thinking of something more local. LocalStorage also appears to be an idea, but it would have to be initialized everytime the browser loaded, and still would be a waste of memory
This question is kind of relative, and some people could even view it as opinion-based. However, I think a concrete answer can be found accounting for some details.
Storing it in the application (arrays/objects)
Yes, that's what you're doing now, and that's what you view like a waste of memory, I know. However, depending on your situation, you shouldn't care too much about that.
Anyway, I'd recommend you to keep your data this way when it is not too large and is unlikely to change. Probably this is not the best alternative for you, since you said you pretend to update the data in the future. It's not only about memory, but also about maintainability.
Local web storage
If the solution above is not suitable for you, probably this also isn't. Why? It's simple. In the process of storing data in localStorage, you'll need to have that data in your code, in the form of an array or object. In the end, you'll have the data in your application AND in the local web storage. It doesn't make much sense, don't you agree?
localStorage should be used for storing data which is relative to the user and which will not be accessible for you after the page is left, unless you save it. This kind of storage would be not be a good choice for storing data that will be accessible for you at any condition.
Using a JSON file
This could be a good solution if your data is not likely to change constantly. And it also would meet your expectations, since you could request data from it only when it's needed. You should take your own situation into account, but, from what I could understand from what you said, that is, you have data which is going to change sometimes and it's somewhat large, using a JSON file would be a good if you don't want to use a database.
Finally, there are several advantages, even for static (but somewhat large) data, of using a database. You could opt, for example, for SQLite, that's an embedded database. However, that is a topic for another question.
For now, since your data will change sometimes and is potentially lengthy, using a JSON file looks like the more suitable option within the "no-database" limits.
localStorage is the way to go.
Just save your object with localStorage.setItem('item', JSON.stringify(obj)) and retrieve it later with JSON.parse.
There's no better way to save data locally in the client side.

Are there benefits to re-defining JSON data as JavaScript objects in source code? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
I'm loading a JSON file from a web server via the XMLHttpRequest in JavaScript. This module, or alternatively the JSON.parse method, returns a JSON Object (a regular JavaScript object, which I call JSON Object as w3schools does).
Loaded JSON data:
{
"MyName":"Kiwi",
"MyNum" : "42",
"MyList" : {
"$type" :"Bla",
"$values: [ ]
}
};
I can pass around the parsed object and access it's properties like a regular JavaScript object. However, I'm wondering if it would make sense to actually declare the object's properties in source code such as:
// MyObject.js
function MyObject() {
this.myName = "Kiwi";
this.myNum = 42;
this.myList = []
}
And basically, map each property from my parsed JSON object to the JavaScript object declared in source code like so (plus additional transformations):
var myObj = new MyObject();
myObj.myName = jsonObject.MyName;
myObj.myNum = jsonObject.MyNum;
I would assume this has benefits such as:
Actual type information such as numbers vs strings
Potentially intellisense/auto-complete features in my IDE
Easier upgrading of data, if the JSON properties ever change
I'm comparing my approach to how JSON is parsed and turned into objects in a language such as C#, using a serializer such as JSON.NET.
Is this also common practice in the JavaScript world or should I stick to just using the JSON objects returned by the JSON.parse method?
Further info:
My special use-case is the handling of JSON data, which includes many meta fields (denoted by names such as "$type" or "$values" to indicate an array). The files were created by JSON.NET and serialize C# objects, which I basically mirror in my JavaScript application. Hence, I might want to re-declare properties more similar to the way the original C# classes were declared. Mainly this would turn calls like myObject.aList.$values[0] into myObject.aList[0].
If you need more than the data types JSON provides, you can roll something yourself to process the items that JSON.parse spits out, or use many libraries like this one
Most peoples use cases are simple enough that they won't need a library that supports more 'rich' data storage, and JSON is fine.
If you know the data structure ahead of time, and need to convert for example a JSON date (stored as a string) into a Javascript date, it's best to just convert it upon loading the JSON. If you have complex needs requiring loading complex data types that you won't be able to predict ahead of time, use a library like Transit.js

javascript - custom data type - what do i need / what should i learn about [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
As js is REALLY flexible language I always wondered if it's possible to create custom data type. Finally I've decided to try to create one. I'm not talking about simple class, rather about something what will behave more like js natives. I'm going to create range data type. Math range like (2.5;9] or (-Infinity;5). Also supporting sums of ranges (2;7] u (9;27). It'd allow to easily create iterators eg 2-8 with 0.25 step. I'd like it to support regular js syntax eg. for... in, or length property calculeted basing on step property.
sadly I've noticed that _iterator_ is supported only in ff but still it should be possible to prepare iterator by making other properties not enumerable.
I know about:
-Object.create/defineProperties
-getters/setters
-use strict (to maximize performance)
-_iterator_ (actually unsupported)
is there anything else that could be usefull?
Atm. I'd do it this way:
I'd create some hidden vars in local scope to precompute iterators after every change of step and store ranges. To make both completly invisible to user. All properties wouldn't be enumerable except steps - theese would be added with iterator recomputing. So simple range [2;7] with step 2 would look like:
local scope:
ranges:[[2;7]] // more arrays if it'd be sum
iterator:[2,4,6]
//other internal variables
not enumerable:
array: // returns copy of iterator using getter
//some other useful properties
enumerable:
0:2
1:4
2:6
Is it good idea, or there are other more proper ways to do it? Would it be possible to allow this class to use operators like +-?
In JavaScript (ed. 5), one
cannot create custom grammar syntax or literal forms;
cannot overload operators
However, many "custom data types" have been created; feel free to create another. For instance, jQuery (manipulate sequences of DOM elements), moment.js (a Date replacement) and big.js (a "big number" type with operations) are all "custom data types" - albeit methods substitute as operators.
Otherwise, not really sure where the rest of the question is going .. except closed.

JSON design best practices [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
I have designed a JSON representation of a mailbox so that I can look up mails easily, for example mailjson[UID].Body.
However after looking at Angularjs and Ember, templating MVC JS engines, it seems that the JSON should be of the format:
[{
"id": 1,
"body": "Blah blah blah..."
},
{
"id": 2,
"body": "More blah foo blah"
},
{
"id": 3,
"body": "Hopefully you understand this example"
}]
And then there is some findAll(id) function to grab the item based on the id one wants, that iterates through the JSON. So now I'm wondering does my JSON design have merit? Am I doing it wrong? Why don't people use the dict lookup design I'm using with my JSON?
Any other tips to make sure I have a good data structure design, I would be grateful.
Best practice for storage of big table in JSON is to use array.
The reason is that when parsing JSON array into memory array there is no speed penalty of building map. If you need to build in-memory index by several fields for quick access, you can do it during or after loading. But if you store JSON like you did, you don't have a choice to load quickly without building map because JSON parser will always have to build that huge map of ids based on your structure.
Structure of how you store data in memory does not have to be (and should not be) the same as structure of storage on disk because there is no way to serialize/deserialize internal JavaScript map structure. If it was possible then you would serialize and store indexes just like MS SQL Server stores tables and indexes.
But if framework that you are using forces you to have same structure in memory and disk then I support your choice of using id as key in one big object, because then it's easier to pass id in JSON requests to and from server to do any action with email item or update it's state in UI, assuming that both server and browser keep significant list of email items in memory.

How should I organize a large JavaScript dialog object? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I have a very large JavaScript object I'm using to store RPG dialog, containing several large top-level objects. The dialog is formatted similar to JSON.
When organizing the dialog, should I put each of those top level categories in their own function?
Or maybe their own separate javascript file?
Does keeping all the text in one javascript (var json =) object affect performance?
Any organization tips would be appreciated!
You should generally try to limit coupling whenever possible. Therefore it would make sense to separate these into separate functions, but see point #3 about databases.
You can separate them into separate javascript files if it gets too big to manage easily with one. You can always have a build process that lumps them all together later (check the html5 boilerplate for more on this technique).
It probably isn't going to make much difference for performance at this point. I might suggest using something like mongoDB in the future as you get more data though. Take a look at meteor js to get some inspiration. Using a database can simplify your code if you do it right.
Addressing question 1, this sounds like JSONP? Slightly different.
I would suggest that performance differences would be negligible for parsing though if using JSONP and injecting <script/> elements to the DOM file size becomes a factor, and it would be wise to group related data into seperate files so that it can be retrieved selectively.
Obviously at the top level if not using JSONP, you can seperate your objects into an array or one keyed object.
I saw your question before the edit and to me it wasn't only about JSON. I understand the reasoning behind meagar's edit but I don't agree with it. I think you should really step out of the technical details and focus on what your data is. You are writing the story of your game in a JSON file. Is that really appropriate or convenient? I personally don't think so. I mean, if you're comfortable working with this so far, sure, knock yourself out. Myself, I would use plain and simple text files to hold that dialog (1 line in a file = 1 line of dialog, with name of file = name of NPC or cutscene) They're much more appropriate for storytelling IMHO.
What I mean is, write that dialog in something that is meant for writing. JSON is a format for data-interchange, sure, it's human-readable. That doesn't mean it should be human-written.
Then, when you have your story, if you want your game to consume that data in JSON form, write some kind of wrapper around this bunch of files. Sure, it looks like more work, but I think it's more flexible. Well, that's what I would do anyway. Best of luck.

Categories

Resources