Saving game in local storage results in [object Object] and undefined - javascript

model is an object that contains every single variable in my code in the form of arrays and objects. I want to save a snapshot of the values within whenever I use the saveGame function, and then redefine it to that snapshot whenever I use the loadGame function. However, when I use loadGame(), it returns [object Object], and then every single piece of information within becomes undefined. What gives?
function saveGame() {
localStorage.setItem('model', model);
}
function loadGame() {
model = localStorage.getItem('model');
updateView();
}

According to MDN web docs, keys and values stored in localStorage are always in UTF-16 DOMString format.
Therefore you can't store an object inside of a localStorage. Since it only accepts strings. The [object Object] you mentioned is a string representation of an object which it automatically creates using the default Object.toString() method.
To convert an object into a string representation and preserve the variables. You could serialize the object into a JSON string using JSON.stringify(). And later deserialize it using JSON.parse() to convert it back into an object.
function saveGame() {
localStorage.setItem('model', JSON.stringify(model));
}
function loadGame() {
model = JSON.parse(localStorage.getItem('model'));
updateView();
}

Related

this.getAttribute() returns an object how can I access to that object?

Doing this.getAttribute('data') returns an object, how can I access to that object to return data.id?
If I do this returns me [object Object].
$(".button").click(function(){
var source = this.getAttribute('data-request');
console.log(source);
   });
And this way returns Undefined:
$(".button").click(function(){
var result = this.getAttribute('data-request');
console.log(result.id);
   });
If this.getAttribute("data-request") is returning "[object Object]", it's because the attribute contains the string "[object Object]", not because it contains an object. Most likely, someone mistakenly did this.setAttribute("data-request", someObject); (or similar). Attributes can only store strings, so doing that automatically converts the object to string, which in most cases results in the string "[object Object]", and then stores that string in the attribute.
That means you can't access the object, because it was never stored to start with, instead, just the "[object Object]" string was stored. (The reason you get undefined for console.log(result.id) is that strings don't have an id property.)
Since you're using jQuery, you have access to jQuery's data function, which can store arbitrary data (which can be anything, not just a string) on a DOM element. So if you really need to store an object attached to a DOM element, find the code doing this.setAttribute("data-request", someObject); or $(something).attr("data-request", someObject); and replace it with $(something).data("request", someObject); That does not set a data-* attribute, but does store the data associated with the element. Then you can retrieve it with const result = $(this).data("request");.
The easiest way to solve this problem is to pass the attribute like a Json String with JSON.stringify(dayBooking) and then parse the json object
let dataDay = e.currentTarget.getAttribute("data-value")
dataDay = JSON.parse(dataDay)

Pass JSON object that contains Array with session.Storage

I'm trying to pass a JSON object using the function session.Storage, in order to keep the object browsing between pages. The JSON object looks like this:
var shapeResult={"accuracy":
{"Syntactic":[], "Semantic":[], "Data_Assurance":[],"Risk":[]},
"completness":
{"Record":[], "Attribute":[],"Completness":[]},
"consistency":
{"Integrity":[]}
};
In my page there's a function that first assigns some values to the empty arrays (as strings) :
var shapeResult={"accuracy":
{"Syntactic":[ID,EMAIL] "Semantic":[ID]}
};
For each of these single value my Function will assign a 0, or a 1. In this way, accessing, for example the object, with this expression:
shapeResult.accuracy.Syntactic
I would obtain either a 0, or 1.
Then I try to save it in the session storage trough
session.Storage.setItem('session_data',JSON.stringify(session_data_temp));
session_data_temp=JSON.parse(session.Storage.getItem('session_data'))
What I obtain from the sessionStorage is the first JSON object, without the added values in the array and the 0's and 1's.
What's the problem?
Use sessionStorage instead of session.Storage
DEMO
var shapeResult={"accuracy":
{"Syntactic":1}
};
sessionStorage.setItem('session_data',JSON.stringify(shapeResult));
var session_data_temp=JSON.parse(sessionStorage.getItem('session_data'));
console.log(session_data_temp);

Javascript - key and value in array

I wish to store some data dynamically in an array, using Javascript. My goal is to save a configuration, that the user has specified, and later store it in my database.
I am trying to create a array like this:
var config = [];
config.push({id:100,name:'Yashwant',age:30});
config.push({id:200,name:'Mahesh',age:35});
However, when I print out the config array, like this:
alert(config);
it prints:
[object Object],[object Object]
How can I store and push values to my array, dynamically?
EDIT:: Seems like I am storing the values correctly. How can I access it?
Alert casts the config parameter to string. If you want to see the value for debugging purposes, it is better to use console.log(config).
Or you could use JSON.stringify(config) to convert it to JSON string.
To access the values, you can do this: console.log(config[0].age, config[1].age);
If you want to print values of any javascript object you can use JSON class to either stringify object data or parse stringified data (JSON) back to object.
alert(JSON.stringify(config));

How do I attach JSON Stringify to a javascript variable

I have a variable :
var testData;
And I have a function that populates an array. Goes through an array and makes another array like so :
var person = {
"Name": obj.Name,
"Age": obj.Age,
}
partsObject.push(person);
I then want to make this array into JSON so I can use it with my D3 objects, so I do this :
testData = JSON.stringify(partsObject);
I can console log this variable, but when trying to go through it via D3's forEach method like so :
testData.forEach(function(d) // data is the JSON
{
I get the error Uncaught TypeError: testData.forEach is not a function
I don't understand how I can log the variable to the console yet it's as if I can't use it as JSON. Any ideas ?
As the name suggests stringify() converts a JavaScript object (the JSO in JSON) into a string of JSON. You can console.log() it because console.log expects to take a string, and anything that's not a string is converted to one to be displayed.
If you want to use it as an array again, you need to parse your string of JSON back to the JavaScript object: JSON.parse(testData).
You really dont need to stringify your Array to pass to d3. Do not to get confused with javascript objects, since forEach requires an array to loop through and you are passing a string to manipulate with forEach function
use:
partsObject.forEach(function(d)
{
...
JSON.stringify(partsObject); creates a string as"{'Name':'ABC','Age':23}"
Uncaught TypeError: testData.forEach is not a function caused because javascript was not able to find an Array
.stringify() turns a Javascript Object into a string. You would want to either run
partsObjects.forEach()
or alternativily you could turn the stringify'ed string back into an object with
(JSON.parse(testData)).forEach()
You are currently trying to loop through a String since you stringify your array.
Just do partsObject.forEach and don't stringify your Array.

How does moment.js know when it's object is being serialised?

From the moment.js docs
moment().toJSON(); When serializing an object to JSON, if there is a
Moment object, it will be represented as an ISO8601 string.
JSON.stringify({
postDate : moment()
}); // {"postDate":"2013-02-04T22:44:30.652Z"}
I don't understand how the moment object can detect the function operating on it. How is it able to return a different value when serialised, and when simply stored in an object, or returned as a string?
When using stringify, an object may define how it gets represented, as shown in this documentation:
From https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/JSON/stringify
toJSON behavior
If an object being stringified has a property named toJSON whose
value is a function, then the toJSON method customizes JSON stringification
behavior: instead of the object being serialized, the value returned by the
toJSON method when called will be serialized.
For example:
var x = {
foo: 'foo',
toJSON: function () {
return 'bar';
}
};
var json = JSON.stringify({x: x});
//json will be the string '{"x":"bar"}'.
moment.js's documentation (seen here: https://raw.github.com/timrwood/moment/2.0.0/moment.js ) shows that this is indeed supported, here is the exact code
toJSON : function () {
return moment.utc(this).format('YYYY-MM-DD[T]HH:mm:ss.SSS[Z]');
}
So, that is how it is aware of how to represent itself when being stringified.

Categories