sessionStorage not storing original object - javascript

I have an object which I'm getting by executing a function of SDK. When I try to store the object in session storage and the retrieve the object, the retrieved object looks same as original but when I perform operations on the new object I'm getting error.
var xyzObject = some_function();
sessionStorage.setItem("xyzObject",xyzObject);
var obj = JSON.parse(sessionStorage.getItem("xyzObject"));
obj.some_other_function();
It is showing an error as obj.some_other_function is not a function. Whereas xyzObject.some_other_function works perfectly.

Try
sessionStorage.setItem('xyzObject', JSON.stringify(xyzObject);
And retrieve using:
JSON.parse(sessionStorage.getItem('xyzObject'));

You cannot store an object in the sessionStorage or localStorage. The only possible method is to stringify the object and save that in sessionStorage and on receiving the object from sessionStorage you just parse the object to JSON.
var xyzObject = some_function();
sessionStorage.setItem("xyzObject",JSON.stringify(xyzObject));
var stringData = sessionStorage.getItem("xyzObject");
var obj = JSON.parse(stringData);
obj.some_other_function();

sessionStorage only stores strings as values.
If you want to store an object in sessionStorage, you must stringify the object into a JSON string, using the JSON.stringify() method.
const xyzObject = { name: "Juan" };
sessionStorage.setItem("xyzObject", JSON.stringify(xyzObject);
Then if you want to read the JSON string stored, you must parse it into a JavaScript object (or value, array, etc) , using the JSON.parse() method.
const xyzObjectRetrieved = JSON.parse(sessionStorage.get("xyzObject"));
// it should equal { name: "Juan" }
Source:
sessionStorage
JSON.stringify
JSON.parse

Related

localStorage into HTML

How would I go on to get the information in the same format as it was saved?
Saved as, example:
document.querySelector('.btn').addEventListener('click', function(event){
const store = {
ci: document.querySelector('.a').innerHTML,
};
localStorage.setItem(store.city, JSON.stringify(store))
This is my code, the storage got different keys:
function myFunction(){
document.querySelector('.a').innerHTML = JSON.stringify(localStorage.getItem(i))}
Although it was not clear to me what is your expectation or expected behavior. But I will try to give an answer with the limited data.
You can get all the keys in localStorage by Object.keys method. And then iterate over the keys and JSON.parse all the localStorage[key].
Object.keys(localStorage).map(key => console.log(localStorage[key]))
That should solve your problem of getting the objects from localStorage.
According to the docs, Storage items can only store data of type DOMString. Converting other data types into a string using the JSON.stringify function is a valid idea!
You only need to reverse this change when reading the data:
function setObjectItem(key, item){
return localStorage.setItem(key, JSON.stringify(item));
}
function getObjectItem(key){
return JSON.parse(localStorage.getItem(key));
}
However, some data types can not be converted into a JSON string. For example, you cannot use this method to store DOM elements.

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

Store a complex object in chrome.storage

I'm writing a chrome extension which needs to store an multidimensional array.
groupList stores another array.
Whenever retrieving the stored object chrome returns an empty array inside of the object.
function Groups(){
this.groupList = [];
}
//some more Code which fills groupList
function saveGroups(){
chrome.storage.local.set({'groups':Groups});
}
function loadGroups(){
chrome.storage.local.get('groups', function (result) {
var groups = result.groups.groupList;
Group.groupList.concat(groups);
});
}
loadGroups returns:
Object
groupList: Array[0]
length: 0
__proto__: Array[0]
__proto__: Object
Local Storage is string only storage.
Use JSON.stringify and JSON.parse before and after saving your complex object to storage.
In order to store arrays you would need to do something like this:
function saveGroups(){
chrome.storage.local.set({'groups':{groupList:[]}});
}

Storing a javascript object in HTML5 local storage

I want to store a JavaScript object in HTML5 local storage.
sessionStorage.setItem("localObj",this);
I am using the above statement within a function.The object contains HTML tags.
I can neither convert it to a string nor to a JSON.
How do i proceed with this?
You have to first convert the object into json and then store in local storage. And when you want to reuse the stored data you have to deserialize the json string into javascript object and it will work fine.
Working Sample
function setValue() {
var obj = new user();
var jsonObject = JSON.stringify(obj);
sessionStorage.setItem("Gupta", jsonObject);
getValue();
}
function user() {
this.Name = "rahul";
this.Age = 20;
}
function getValue() {
var json_string = sessionStorage.getItem("Gupta");
var obj = JSON.parse(json_string)
alert("Name = "+obj.Name + ", Age = " + obj.Age);
}
Local storage will only store strings. If you can't make a string representation of your object, then you can't store it.
Local storage is designed with string / value pairs in mind, so you'll have a hard time trying to store your object 'as is'. You either need to 'stringify' it, or you need to look at something else. The answers to this earlier question should assist:
Storing Objects in HTML5 localStorage

localStorage - append an object to an array of objects

I'm attempting to locally store an object within an array within an object.
If I try the following in my console it works perfectly:
theObject = {}
theObject.theArray = []
arrayObj = {"One":"111"}
theObject.theArray.push(arrayObj)
However if I do what I think is the equivalent, except storing the result in localStorage it fails:
localStorage.localObj = {}
localStorage.localObj.localArray = []
stringArrayObj = JSON.stringify(arrayObj)
localStorage.localObj.localArray.push(stringArrayObj)
I get the following error...
localStorage.localObj.localArray.push(stringArrayObj)
TypeError
arguments: Array[2]
message: "—"
stack: "—"
type: "non_object_property_call"
__proto__: Error
Any idea how I can get this to work?
Cheers
You can only store strings in localStorage. You need to JSON-encode the object then store the resulting string in localStorage. When your application starts up, JSON-decode the value you saved in localStorage.
localObj = {}
localObj.localArray = []
localObj.localArray.push(arrayObj)
localStorage.localObj = JSON.stringify(localObj);
...
localObj = JSON.parse(localStorage.localObj);
LocalStorage can store only key-value pairs where key is string and value is string too.
You can serialize your whole object hierarchy into JSON and save that as localStorage item.
According to V8 sources (I assume you using Google Chrome but hope this isn't different for other JS engines) TypeError with message 'non_object_property_call' occurs than method called on undefined or null value.

Categories