javascript - Parsing retrieved localStorage item brings undesired result in console -
i making note web app using localstorage, when user submits note, values input , textarea saved in object.
each note created object containing key/value pairs
- id: 0
- title: value input
- content: value textarea
after localstorage contains least 1 item string on in when new note created, get/retrieve localstorage string contain past entered notes in string format.
parse localstorage string , save variable/array have prior notes add on to.
push new input values saved input object each time, array before setting localstorage item array(stringifying of course).
below function that's responsible saving note localstorage
// user clicks save note post_note_button.onclick = function() { // values input , textarea var note_title = document.getelementbyid("note-title").value; var note_textarea = document.getelementbyid("note-textarea").value; // each time note created, new values input saved var input = { id: note_id_count, title: note_title, content: note_textarea }; // ------------------------------------------------ switch(localstorage.getitem("note")) { // if retrieve localstorage item returns false/doesn't exist // purpose: set localstorage string first time // 1. create localstorage item values user's input case null: localstorage.setitem("note", json.stringify(input)); break; // if retrieve localstorage item returns true/exists // purpose: retrieve localstorage string , manipulate // 1. changing localstorage string, requires string retrieved , saved array // 2. add item array // 3. create/set localstorage item values array, convert 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 console.log & parse localstorage item "note" after adding few notes, should get
array [ object, object, object ]
instead get:
array [ array[2], object ]
codepen: http://codepen.io/anon/pen/jdjmyq
it looks when save first item localstorage (when there nothing there), saving object. when add next item, wrap in array.
instead save original object wrapped in array, , push onto 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 forked codepen