1

I think, my question is very easy, but I never work with JSON and localStorage. So, I have a function, which returns an object and a loop, which fires the function n-times and create n-objects.

function result(){
  //some other functions
  let finalObj = {
           "Потяг №" : getTrainNumber(),
           "Пункт відправлення" : cities[randomCity_A],
           "Пункт прибуття" : cities[randomCity_B],
           "День тижня" : getDepartureDay(),
           "Відправлення" : mergedDepartureTime(),
           "Вартість" :  getTicketPrice()
        };

   return finalObj;
}

var firingCount = prompt('Trains count', 10);
  for(var i = 0; i < firingCount; i++) {
  console.log(result());

  let serialObj = JSON.stringify(result());
  localStorage.setItem("myKey", serialObj);
}

How can i save all created objects in localStorage (it saves only 1 finalObj), and if i can save all objects in other .json file, how to do it? Thank you.

1
  • Push all the objects into an array and then save that array to localStorage. Commented Dec 17, 2017 at 10:45

1 Answer 1

2

You are setting object (serialObj) in the same key (myKey) again and again. That's why the key is only retaining the last object.

Try to create unique key like the following:

var firingCount = prompt('Trains count', 10);
for(var i = 0; i < firingCount; i++) {
   console.log(result());

   let serialObj = JSON.stringify(result());
   localStorage.setItem("myKey" + i, serialObj); // create unique key by appending i to "myKey".
}
Sign up to request clarification or add additional context in comments.

1 Comment

@АртемМирошниченко, You are most welcome. Please accept the answer if it helps.....thanks.

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.