localStorage into HTML - javascript

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.

Related

retrieve key names from firebase react-native

I have a little problem regarding Firebase and retrieving names of parent keys. Like in this example I want to get the names of the keys, not their values:
Pls have a look in my db how it looks now, its exactly the same like in the JS sandbox:
When I try to implement this in my react-native project, basicly with plain JS in this part, it looks like this:
const sendletter = () => {
console.log("letter send");
firebase.database().
refFromURL("https://SOMEDATABASE.firebaseio.com/numers").
once("value").then(snapshot => {
for(key in snapshot){
console.log(key)
}
})
};
The problem I just face now it the outcome of the console in my IDE:
null letter send node_ ref_ index_ val exportVal toJSON exists child
hasChild getPriority forEach hasChildren key numChildren getRef ref
I tried to provide you as many pictures so the problem gets really clear and also my goal I want to archieve, to get the key names itself, NOT the values the keys are linked to. Any help would be appriciated!
You want to use snapshot.val() instead of just the DataSnapshot object
for(key in snapshot.val()){
console.log(key);
}
When you are looping through just the snapshot variable, you are looking at all the keys in that DataSnapshot that is returned from firebase and not your actual data. If you check out Firebase docs, you'll see what the DataSnapshot object represents and how to actually get your data from the database FROM their DataSnapshot object that is returned: https://firebase.google.com/docs/reference/node/firebase.database.DataSnapshot
If you look close enough you can see that all the methods and values that this DataSnapshot object contains is actually what was being printed in your console all along

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 Object not fully converts to String?

I am facing an issue that JSON.stringify not stringifies all the keys in a JSON Object.
ie. window.performance.getEntries()[0] contains around 17 keys. But on converting to a string, the result contains only 4 keys.
How can I convert all the keys in window.performance.getEntries()[0]?
I want the complete string output of window.performance.getEntries() which is an array and I used JSON.stringify(window.performance.getEntries()).
Thanks in advance..
window.performance seems to have is own toJSON-function and so can determine what will be stringified. Here is a answer and a work around to your question from a similiar question: https://stackoverflow.com/a/20511811/3400898
"If the stringify method sees an object that contains a toJSON method, it calls that method, and stringifies the value returned. This allows an object to determine its own JSON representation."
As other stated it is because there is a toJSON method defined. Basically you need to loop over every index of the array and than every property in the object.
var adjusted = window.performance.getEntries().map( function (result) {
var temp = {}, key;
for (key in result) if (key!=="toJSON") temp[key]=result[key];
return temp;
});
console.log(JSON.stringify(adjusted[0]));
The simplified solution for this problem which I found is
var jsonArray = $.map(performance.getEntries(),function(jsonObj){
var obj = $.extend({},jsonObj);
delete obj.toJSON;
return obj;
});
JSON.stringify(jsonArray);

JSON.stringify turned the value array into a string

I have a JS object
{
aString:[aNumber, aURL]
}
JSON.stringify() returns
{
"aString":"[number, \"aURL\"]"
}
I thought that valid JSON can have arrays as values. Can I have stringify return the JSON string without converting the array into a string? Basically I need turn the whole JS object straight into a string, without any modification.
Is there a better way to do this? I've been looking around but everyone suggests using JSON.stringify if I want an object to string, and no one has raised this problem.
EDIT: Thanks for the quick responses. Here is how I created my JS object, please let me know if I messed up and how!
cookie = {};
// productURL is a string, timer is a number, imageSrc is a URL string
cookie[productURL] = [timer, imageSrc];
// then, I just stringified cookie
newCookie = JSON.stringify(cookie);
If it is also relevant, I am setting an actual cookie's value as the resulting JSON string, in order to access it in another set of functions. Setting the cookie's value does do some URI encoding of its own, but I've actually been grabbing the value of newCookie in the Chrome console as well and it also returns the Array as a string.
If an object you're trying to stringify has a toJSON function, that will be called by JSON.stringify. Most likely you have an external library that's adding Array.prototype.toJSON.
For example, an old version (1.6) of Prototype JS will "conveniently" add that for you.
Prototype 1.6.1:
alert(JSON.stringify([1, 2, 3]));
<script src="https://cdnjs.cloudflare.com/ajax/libs/prototype/1.6.1/prototype.min.js"></script>
Whereas a newer version will not.
Prototype 1.7.2:
alert(JSON.stringify([1, 2, 3]));
<script src="https://cdnjs.cloudflare.com/ajax/libs/prototype/1.7.2/prototype.min.js"></script>
You could try deleting Array.prototype.toJSON just to see if that's what's causing the problem. If it is, you might want to look into upgrading/deprecating any libraries in your code that do weird things like that.
Prototype 1.6.1 (after deleting toJSON)
delete Array.prototype.toJSON;
alert(JSON.stringify([1, 2, 3]));
<script src="https://cdnjs.cloudflare.com/ajax/libs/prototype/1.6.1/prototype.min.js"></script>
Based on your description this is not what should happen.
If you have code like this:
var obj = {
aString:[123, "test"]
}
document.getElementById("out").value = JSON.stringify(obj);
it will generate the expected json:
{"aString":[123,"test"]}
also see https://jsfiddle.net/zudrrc13/
in order to produce your output the original object would have to look something like:
var obj = {
aString:"[123, \"test\"]"
}

HTML5 localstorage methods advantages?

I've been using localStorage and a question came to me:
Which is the advantage using setItem and getItem methods rather than:
SET ITEM : localStorage.myKey = "myValue";
GET ITEM : localStorgae.myKey --> returns "myValue"
Are they just helper methods then? Good practices?
Just about curiosity thanks.
HTML5 Storage is based on named key/value pairs. You store data based on a named key, then you can retrieve that data with the same key. The named key is a string. The data can be any type supported by JavaScript, including strings, Booleans, integers, or floats. However, the data is actually stored as a string. If you are storing and retrieving anything other than strings, you will need to use functions like parseInt() or parseFloat() to coerce your retrieved data into the expected JavaScript datatype.
interface Storage {
getter any getItem(in DOMString key);
setter creator void setItem(in DOMString key, in any data);
};
Calling setItem() with a named key that already exists will silently overwrite the previous value. Calling getItem() with a non-existent key will return null rather than throw an exception.
Like other JavaScript objects, you can treat the localStorage object as an associative array. Instead of using the getItem() and setItem() methods, you can simply use square brackets. For example, this snippet of code:
var foo = localStorage.getItem("bar");
// ...
localStorage.setItem("bar", foo);
…could be rewritten to use square bracket syntax instead:
var foo = localStorage["bar"];
// ...
localStorage["bar"] = foo;
Maybe this hope. :D
Reference: http://diveintohtml5.info/storage.html
set/getItem are better than property-access for the following reasons:
localStorage coerces all its input into strings, but you can overwrite the set/getItem methods to perform serialization and deserialization to support types other than strings:
var basicSetItem = localStorage.setItem;
localStorage.setItem = function(key, val) {
basicSetItem.call(localStorage, key, JSON.stringify(val));
}
var basicGetItem = localStorage.getItem;
localStorage.getItem = function(key) {
return JSON.parse(basicGetItem.call(localStorage, key));
}
You cannot achieve an equivalent effect for all storage property values using ECMAScript 5 APIs.
You cannot set the storage key length, and you cannot access the keys getItem, setItem, or removeItem without using function access:
localStoage.length = "foo"; // does not work
localStoage.setItem("length", "foo"); // works
var bar = localStoage.setItem; // gets the `setItem` function
var bar = localStorage.getItem("setItem"); // gets the value stored in the `setItem` key

Categories