0

I want to store data locally for each sub object returned in json format like this -

key - name sectionType+number of section type ,  value - this object

My existing JS code:

function syncAllSections_4(){
        user_sections= loggeduser_array.id;
        console.log(user_sections);
         var dict_4 = { userId: user_sections };
 $.ajax({
    url: 'http://funiks.com/adminv7/offline-api/listSections.php',
    type: 'POST',
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    data: JSON.stringify(dict_4),
})
.done(function(data, textStatus, jqXHR) {
    if(data.status=="SUCCESS") {
    localStorage.setItem("sections",JSON.stringify(data.sections));
    //console.log(JSON.parse(localStorage.getItem("sections")));
    
    var sections_array = [];
    sections_array  = JSON.parse(localStorage.getItem("sections"));
    }
}).fail(function(jqXHR, textStatus, errorThrown) {
    alert("error");
});
    }

The data format returned in Json is:

https://pastebin.com/4XBR23ua

This is how I want to save it in local storage:

enter image description here

2
  • What have you tried that has not worked? Commented May 14, 2017 at 6:24
  • I am trying to break the json and for that i need to call it in an array which i am doing but its not giving me the right length, this is how i am trying var sections_array = []; sections_array = JSON.stringify(data.sections); console.log(sections_array.length); Commented May 14, 2017 at 10:49

1 Answer 1

1

It seems that "sections" is already an array, so you shouldn't stringify it for array length. Also, the solution is quite straightforward (not tested but should work):

function syncAllSections_4(){
  user_sections= loggeduser_array.id;
  console.log(user_sections);
  var dict_4 = { userId: user_sections };
  $.ajax({
      url: 'http://funiks.com/adminv7/offline-api/listSections.php',
      type: 'POST',
      contentType: 'application/json; charset=utf-8',
      dataType: 'json',
      data: JSON.stringify(dict_4),
  })
  .done(function(data, textStatus, jqXHR) {
    if(data.status=="SUCCESS") {
      data.sections.forEach(section)=>{
        localStorage.setItem("SectionTypes"+section.sectionType,JSON.stringify(section));
      })
    }
  }).fail(function(jqXHR, textStatus, errorThrown) {
    alert("error");
  });
}

Sign up to request clarification or add additional context in comments.

1 Comment

thanks a lot, i also figured it out, i did it like this - sections_array = data.sections; console.log(sections_array.length); for(i = 0; i < sections_array.length; i++){ localStorage.setItem("section"+sections_array[i].sectionType,JSON.stringify(data.sections[i])); console.log(sections_array[i].sectionType); }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.