Parsing retrieved localStorage item brings undesired result in console - javascript

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

Related

How to save multiple form values as a consolidated String in Local Storage and retrieve them to be displayed on the browser

I'm trying to create a 'Notes' application which is basically a form that the user uses to enter 2 values, a name and a note.
I am displaying the 2 values as a 'consolidated note' on the browser with a delete button.
There can be any number of notes entered using this form.
How can I save the consolidated notes(i.e with Creator's name and the actual content of the note) in a string or array in the Local Storage and then retrieve it to be displayed on the browser when the browser reloads?
I understand that we save it using JSON.stringify and retrieve the data from the Local Storage using JSON.parse, but I'm unsure of how to save these multiple notes in the LOCAL Storage and retrieve them. Please help!
function addNoteLocalStorage(){
let notes = getNotesFromStorage();
//creating the key-value pairs
let creator = document.getElementById('creator').value;
let note = document.getElementById('note').value;
obj.creator = creator;
obj.note = note;
let jsonstring = JSON.stringify(obj);
//create an array and push the string to the Object Array
objArray.push(jsonstring);
//store the new note
localStorage.setItem('notes', objArray);
}
The above code saves more than one note in the Local Storage.
Currently, this is how the array looks when stored in LS.
{"creator":"dgfdxsf","note":"dsgdsg"},{"creator":"sfs","note":"asd"}
How can I retrieve the values back into an object so that I can display each creator and note associated with that creator ?
Create an object of the values you get from the form.
var obj = {
creator : note
}
Now store this object in the local storage by stringifying in the same as you are doing (JSON.stringify). While retrieving, do a JSON.parse to retrieve the object.
If you have multiple objects like these, push them into an array and store that array in the local storage.
There is no need to convert a string to a JSON string, so you can play with your data without the need for stringify() and parse(). If you save the notes as array, however, you will need to do that.
// Add Note to Local Storage
function addNoteLocalStorage(){
//get saved notes. Set notes to empty string if it's the first time.
let notes = localStorage.getItem('notes') || '';
console.log("Notes return: "+notes);
//creating the key-value pairs
let creator = document.getElementById('creator').value;
let note = document.getElementById('note').value;
let consolidatedNotesString = creator+":"+note;
//append the new note to the existing note
notes += '\n'+ consolidatedNotesString;
//store the new note
localStorage.setItem('notes', notes);
}
With your edited question, you're saving notes in the form of array of objects, in which case you will of course need to stringify and parse back the notes. One issue with your current code is that you're converting to string the objects(notes) but you save the array which contains the notes as it is. stringify the whole array instead and that's enough. And the way you access the stored notes is by the getItem method and parse it to get back the array. Make sure to save the empty objArray as notes in the local storage before calling addNoteLocalStorage function though, or you will need to check if notes are already in the storage before trying to parse it.
const objArray = [];
localStorage.setItem('notes', JSON.stringify(objArray));
function addNoteLocalStorage(){
objArray = JSON.parse(localStorage.getItem('notes'));
//creating the key-value pairs
let creator = document.getElementById('creator').value;
let note = document.getElementById('note').value;
//push the string to the Object Array
objArray.push({creator, note});
//store the new note
localStorage.setItem('notes', JSON.stringify(objArray));
}
//And to get the first note and creator for example, you write like:
let noteArray = JSON.parse(localStorage.getItem('notes'));
let firstNoteCreator = noteArray[0].creator;
let firstNote = noteArray[0].note;

Using localStorage/sessionStorage to store arrays

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]

JQuery Mobile JSON Stringify

I'm new in jquery mobile. I'm doing a shopping list application for my school assignment and I'm requested to store objects in local storage.
Each item must include the following information: item Name, item quantity and a Boolean is_bought.
I wish to store all items data into one JSON string. Items data is entered by user from an other page.
My problem is
1)How items can be stored in local storage through JSON stringify.
2)How items data can be retrieved from JSON string to be represented into a list.
First: If I understood you right you have an object(json) structure like:
{
"name": "cheese",
"quantity": 2,
"is_bought": false
}
If not (in question you have no key(name) for your variables) your structure must be like I showed for having an access to each variable in the object.
Second: About localStorage. It is limited to handle only string key/value pairs, so you can't just save an object in it. You have to use JSON.stringify() to parse your object into the string and save in localStorage, then, after retrieving, use JSON.parse() to parse it back. The code could look like this:
var item = {"name": "cheese", "quantity": 2, "is_bought": true};
// Store item into localStorage
localStorage.setItem('item', JSON.stringify(item));
// Retrieve item from localStorage
var retrievedItem = localStorage.getItem('item');
var parsedItem = JSON.parse(retrievedItem);
EDIT: TO STORE MULTIPLE ITEMS
So, if your question is about storing multiple items and distinguishing them, and if your item's name is unique and you know what item is bought, you can store them into the localStorage with the key of item's name, e.g.
// You can do this in a for loop
localStorage.setItem('item_' + item.name, JSON.stringify(item));
// And to change (if you already know bought item's name), 'cheese' for example
var retrievedItem = localStorage.getItem('item_cheese');
var parsedItem = JSON.parse(retrievedItem);
parsedItem.is_bought = true;
// And save again in localStorage
localStorage.setItem('item_cheese', JSON.stringify(parsedItem));

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

how to remove element from session storage array when there are lot of

I am trying to remove elements from localStorage array. all i could find is localStorage.removeItem(key);
I couldn't understand how it works because I have 2 sessionStorage. is that okay?
I have this so far
var theCart = JSON.parse(sessionStorage.getItem("ProductName")); // Retrieving
var quantity = JSON.parse(sessionStorage.getItem("QuantityOFprod"));
var prodprice = JSON.parse(sessionStorage.getItem("sum"));
ProductName, QuantityOFprod and sum is arrays.
I don't now how to form the localstorage.removeItem to select the array and then select an element inside the array. I have tried this
sessionStorage.removeItem("ProductName", JSON.stringify(namee));
namee is the a variable which contains the element I want to delete inside the specific sessionStorage array. But all it was doing is deleting everything.
You have to do this way:
read the entry
decode from JSON
remove the element
encode to JSON
update the entry
tmp = JSON.parse(sessionStorage.getItem("ProductName"));
delete tmp["key to remove"];
sessionStorage.setItem("ProductName", JSON.stringify(tmp));
Done.

Categories

Resources