Store a complex object in chrome.storage - javascript

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:[]}});
}

Related

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

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

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

sessionStorage not storing original object

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

JSON / JavaScript get object keys

I'm extracting data from as follows -
The above function returns data in the below format -
[Object { date=Date, value=112, volume=1469}, Object { date=Date, value=124, volume=539}, Object { date=Date, value=114, volume=859}, Object { date=Date, value=123, volume=1284}, Object { date=Date, value=113, volume=1382}, Object { date=Date, value=129, volume=1353}]
I would like to obtain the list of keys only as a simple array.(Parsing the first object in the array is enough to get this as all other objects have the same keys) In case of the above output, I would like the simple array to look as ["date","value","volume"]
I tried JSON.stringify & then parse but it still doesn't work.
Also, how could I convert the whole array obtained from the chart into a simple array please?
I'm visualizing an output of the below type -
[{'date':'whatever', 'value':126, 'volume':911},
{'date':'whatever', 'value':136, 'volume':1005},
{'date':'whatever', 'value':125, 'volume':720}]
If the question doesn't make sense, please let me know. I'll see how best I could re-word.
Use Object.keys() function. Here in the response from function you get an array. Use that to get the list of keys.
var data = getChartData('param')
Object.keys(data[0]);

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