Faced such a problem! Adding an element to the beginning of the array. The procedure I numbered, and the code laid out here .
The array is called Returned_Json. The bottom line is simple. Add comments to localStorage.
I will be very grateful!

Once again link ( http://codepen.io/Brave_Lime/pen/PzzwXm?editors=0010 )

Here is the main piece:

function main_json(a){ if(a==0){ //6 localStorage.setItem('LocalStorage', Returned_Json); //Здесь Обновиться localStorage console.log(localStorage.LocalStorage); } else { // 3 Returned_Json = JSON.parse(localStorage.getItem('LocalStorage'));//Здесь он создается console.log(Returned_Json); return Returned_Json; } }; function post_comment() { //2 $.each(main_json().posts, function(i, post){ //7 var list='<div>'; ... list+='</div>'; $("#Main_Content_Comment").append(list); }); }; function post() { //4 main_json().posts.unshift( //**//Здесь должен изменяться - Основная проблема! Не добавляется в массив. { "time": '10', }); var a=0; console.log(main_json().posts); console.log(Returned_Json); console.log(localStorage.LocalStorage); main_json(a); //5 post_comment(); }; $(document).ready(function() { post_comment(); }); 

Problem: in main_json().posts (in fact, this is an array of Returned_Json ) the specified element is not added. What stupid further performance ...

  • Without the content of main_json question is too wide, as well as without post_comment . In addition, in the last question we decided that we just need to write the modified array back to localStorage - Grundy
  • @Grundy I posted all the code. ( codepen.io/Brave_Lime/pen/PzzwXm?editors=0011 ) - Brave_Lime
  • the necessary code should be directly in the question; links can only be an addition. Also, read how to create a minimal reproducible example - Grundy
  • besides, the link has too much unnecessary text, and these items are lost in them, as a result: a lot of code that does not understand what it is doing and it is not clear in which part the problem - Grundy
  • Yeah, now it only remains to formulate the problem: what exactly is going wrong? Are there any errors in the console? Nothing happens? Any unexpected behavior? - Grundy

1 answer 1

As it turned out, the main problem was in the incorrect update of the data in localStorage

 localStorage.setItem('LocalStorage', Returned_Json); //Здесь Обновиться localStorage 

localStorage allows storing only strings, so in this case the Returned_Json object will be cast into a string, usually "[object Object]" and this value will already be written.

To remedy the situation, use the stringify method of the stringify object , which just translates the object into a string in the form of JSON.

Thus, this line should look like this:

 localStorage.setItem('LocalStorage', JSON.stringify(Returned_Json)); //Здесь Обновиться localStorage