Adding objects to localStorage. JSON

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.

Upvotes: 1

Views: 63

Answers (1)

Mamun
Mamun

Reputation: 68933

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".
}

Upvotes: 2

Related Questions