Using localStorage/sessionStorage to store arrays - javascript

I am trying to save an array inside of a localStorage value. I can only access chars of the value, not the grouped value. I have been trying to write a function to group them by commas, but I can't figure out how to do it correctly.
// setting values
localStorage.setItem("foo", [15,"bye"]);
// writes the whole thing.
document.write(localStorage.getItem("foo")); // returns 15,bye
// only writes the first character, instead of one part of the array
// (in this case it would be 15).
document.write(localStorage.getItem("foo")[0]); // returns 1

I would use JSON.stringify to set the data and JSON.parse to fetch the stored data.
Try this:
localStorage.setItem("foo", JSON.stringify([15,"bye"]));
// writes the whole thing.
localStorage.getItem("foo"); // returns 15,bye
var data = JSON.parse(localStorage.getItem("foo"));
console.log(data[0])

localStorage can only store string in its value, that is why it is storing only 15;
Use JSON.stringify and store it in the local storage as localStorage.setItem("foo",JSON.stringify([15,"bye"]));
If you want to retrieve the value do as JSON.parse(localStorage.getItem("foo"));

You can parse json
let data = JSON.parse(localStorage.getItem("foo"));
console.log(data[0])
Or you can split by ',' and get the 0th index item.
localStorage.getItem('foo').split(',')[0]

Related

Access nested object values from local storage

How to get nested object values from localstorage.
For example:
"metadata":"{
"receiver":{"name":"John"},
"document":{"type":"Sample doc"},
"issuer":{"signatory":"Admin2"}}",
"options": "{"title\":"Document Title","expireOn":"2022-03-12T00:00:00.000Z"}"
I need to store and get values of name:john, type:sample, signatory:Admin.
localStorage.setItem('metadata', JSON.stringify(data.metadata));
let metadata = localStorage.getItem('metadata');
console.log('metadata: ', JSON.parse(metadata));
Thank you.
At first you should get the localStorage values and convert that to a JavaScript Object.
let metadata = JSON.parse(localStorage.getItem('metadata'))
Then you can easily get or store data.
// Store
metadata.receiver.name = 'example'
// Get
let name = metadata.receiver.name
You can do this way for other values also.
Have tried to save and get your JSON in localstorage.
Steps for getting nested object value.
Step 1: Sample JSON
var data = {"metadata":{"receiver":{"name":"John"},"document":{"type":"Sampledoc"},"issuer":{"signatory":"Admin2"}},"options":{"title":"DocumentTitle","expireOn":"2022-03-12T00:00: 00.000Z"}};
Step 2: Converting JSON Object to a String format and Save in
Localstorage window.localStorage.setItem("metadata", JSON.stringify(data.metadata));
Step 3: Fetch Stringify JSON from localstorage and parse var metadata = JSON.parse(window.localStorage.getItem("metadata"));
Step 4: Fetch nested Object value console.log(metadata.receiver.name)
Hope this answer is useful.

Can a localStorage value be an object or array?

I am trying to set storage in the user's computer with localStorage("save","{teams:5, points:20}, etc. But I'm not sure if the value can be an object. I've checked the internet, but I can't seem to find clear answers there.
var data={
teams:5, points:25,team1:5,team2:10, team3:5, team4:0, team5:5};
localStorage ("save", data);
Thoughts?
No, the key and value must be a DOMString. See https://developer.mozilla.org/en-US/docs/Web/API/Storage/setItem
What you can do is serialise your data as JSON before setting it
localStorage.setItem('save', JSON.stringify(data))
When reading the value, you can parse it back into an object
let saveData = JSON.parse(localStorage.getItem('save'))
local storage limited to handle only string key/value pairs you can do like below using JSON.stringify and while getting value JSON.parse
var testObject = { {name:"test", time:"Date 2017-02-03T08:38:04.449Z"} };
// Put the object into storage
localStorage.setItem('testObject', JSON.stringify(testObject));
// Retrieve the object from storage
var retrievedObject = localStorage.getItem('testObject');
console.log('retrievedObject: ', JSON.parse(retrievedObject));
No, localstorage takes string as and saves it. If you want to save any object then convert it on string and then save it.
while fetching it from local storage you we get string. you may easily covert it into object.
if you directly save an object into localStorage then it will be saved in such manner "[object Object]" and while fetching it from localStorage, you will get "[object Object]" as String.
Wrong Code:
var data={teams:5, points:25,team1:5,team2:10, team3:5, team4:0, team5:5};
localStorage.setItem("save", data);
localStorage.getItem("save")
you will get "[object Object]"
Right Code:
var data={teams:5, points:25,team1:5,team2:10, team3:5, team4:0, team5:5};
localStorage.setItem("save",JSON.stringify(data));
localStorage.getItem("save")
While fetching value from localStorage
Wrong Code:
localStorage.getItem("save")
It will fetch data in form of string.
Right Code:
JSON.parse(localStorage.getItem("save"))
It will return data in form of object.
I hope the solution is well explained.
No, It can't be but you can use stringify. For example:
localStorage.setItem('user', JSON.stringify(r.user));
You need to use the localStorage.setItem(keyName, keyValue);
For Storing a Object, you can make use of JSON.stringify(object) which converts the object to a string.
From MDN
keyName
A DOMString containing the name of the key you want to
create/update.
keyValue
A DOMString containing the value you want to
give the key you are creating/updating.

Parsing retrieved localStorage item brings undesired result in console

I am making a note web app using localStorage, when user submits a note, the values from the input and textarea are saved in a object.
Each note created is a object containing key/value pairs
id: 0
title: value from input
content: value from textarea
After localStorage contains least one item with a string from then on in when a new note is created, I get/retrieve the localStorage string which will contain past entered notes in string format.
Parse the localStorage string and save it into a variable/array to have the prior notes to add on to.
Push new input values saved into input object each time, to the array before setting the localStorage item with the array(stringifying it of course).
Below is the function that's responsible for saving the note into localStorage
// User clicks to save note
post_note_button.onclick = function() {
// Get values from input and textarea
var note_title = document.getElementById("note-title").value;
var note_textarea = document.getElementById("note-textarea").value;
// Each time note is created, new values from input will be saved
var input = { id: note_id_count, title: note_title, content: note_textarea };
// ------------------------------------------------
switch(localStorage.getItem("note")) {
// If retrieve for localStorage item returns false/doesn't exist
// PURPOSE: Set localStorage string for first time
// 1. Create localStorage item with values from user's input
case null:
localStorage.setItem("note", JSON.stringify(input));
break;
// If retrieve for localStorage item returns true/exists
// PURPOSE: To retrieve localStorage string and manipulate it
// 1. Changing localStorage string, requires string to be retrieved and saved as array
// 2. Add item to array
// 3. Create/set localStorage item with values from array, convert to string
default:
var note_array = [JSON.parse(localStorage.getItem("note"))];
console.log(note_array);
note_array.push(input);
localStorage.setItem("note", JSON.stringify(note_array));
break;
}
// ------------------------------------------------
};
MY PROBLEM:
When I console.log & parse the localStorage item "note" after adding a few notes, I should get
Array [ Object, Object, Object ]
instead I get:
Array [ Array[2], Object ]
codepen: http://codepen.io/anon/pen/JdjMYq
It looks like when you save the first item into the localStorage (when there is nothing there), you are just saving it as an object. Then when you add the next item, you wrap it in an array.
Instead you could save the original object wrapped in an array, and then just push onto that one:
case null:
localStorage.setItem("note", JSON.stringify([input]));
break;
--
default:
var note_array = JSON.parse(localStorage.getItem("note"));
console.log(note_array);
note_array.push(input);
localStorage.setItem("note", JSON.stringify(note_array));
break;
See this forked codepen

Remove json object in localstorage using js

[{'id':1,'content':'something'},{'id':2,'content':'something diff'},{'id':3,'content':'something diff'}]
by localStorage.getItem('data') I got the above json object, but how to delete the id 2 item?
Assuming you've JSON.parse'd your local storage data into an array, you can remove the second item like you would from any other array- by popping it off.
var data = localStorage.getItem('data');
// At this point, data is either null or a string value.
// To restore the string to an Array you need to use JSON.parse
if (data) {
data = JSON.parse(data);
// At this point you can use Array methods like pop or splice to remove objects.
}
// At this point, your Array will only contain the first item.
// If you want to write it back to local storage, you can like so:
// Be sure to use JSON.stringify so it can later be restored with parse.
localStorage.setItem('data', JSON.stringify(data));
This will turn "data" into a javascript object and remove the last item (assuming this is always an array):
var data = localStorage.getItem('data');
if (data) {
data = JSON.parse(data);
data.pop();
}

Store object from local storage into variable

I am trying to retrieve a object from localstorage and trying to load it into a variable . How can i do this ? This is where i m stuck
var messageStorage={};
messageStorage.retrieve = function () {
var storageString = localStorage.getItem(credentials.mobileNumber);
var storageObj = JSON.parse(storageString);
// whats should go here for messageStorage to be equal to storageObj
};
On messageStorage.retrieve(); the variable messageStorage must contain the value from localstorage.
with localStorage the data is actually stored as a string.
And you use JSON.parse to return the value
JSON.parse() Returns the Object corresponding to the given JSON text.
Example :
JSON.parse('{}'); // {}
JSON.parse('true'); // true
JSON.parse('"foo"'); // "foo"
JSON.parse('[1, 5, "false"]'); // [1, 5, "false"]
JSON.parse('null'); // null
But i saw that you want to return the variable. So what's the type of this variable ? Number, String, Boolean ? You can convert from String to what you need
localStorage allows you to save only strings, so if you have to save an object you should save it as a JSON string or you can use this library to solve your issue
first of all we can't store objects to localstorage, only strings are allowed:
localStorage.setItem("test", JSON.stringify(jsondata));
var item = JSON.parse(localStorage.getItem("test"));
now you have json data to parse it and get the value.

Categories

Resources