Storing items in localStorage with JSON encoding

Although I am not familiar with JSON and localStorage, I have a function that returns an object and a loop that repeats the function n times to create n objects.

function result(){
  //some other functions
  let finalObj = {
           "Train Number" : getTrainNumber(),
           "Departure Point" : cities[randomCity_A],
           "Arrival Point" : cities[randomCity_B],
           "Day of the Week" : getDepartureDay(),
           "Departure Time" : mergedDepartureTime(),
           "Cost" :  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);
}

I need assistance in saving all created objects in localStorage (it currently saves only 1 finalObj). Additionally, if possible, how can I save all objects in another .json file? Thank you.

Answer №1

You keep overwriting the object (serialObj) with the same key (myKey) repeatedly, causing it to only hold onto the last object.

Consider generating unique keys using this approach:

var trainCount = prompt('Enter number of trains', 10);
for(var i = 0; i < trainCount; i++) {
   console.log(getTrainDetails());

   let serialObj = JSON.stringify(getTrainDetails());
   localStorage.setItem("trainKey_" + i, serialObj); // Append i for a distinct key.
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Effortless scrolling implementation

How can I make the scroll smooth and animated with this code structure? Check out my JSFiddle here: https://jsfiddle.net/v7qhzo8q/ The code structure is as follows: <nav id="nav"> <ul id="top"> <li><a href="#">Home</a> ...

Singling out a particular navigation tab

When attempting to link specific table IDs so that the corresponding tab is active when opened (i.e. www.gohome.com/html#profile), I am facing an issue where the active tab remains unchanged. Even after specifically calling out tab IDs, there seems to be n ...

Preventing redirection post-AJAX call using jQuery

Currently, I am attempting to implement a basic form submission using AJAX to send data to submit.php for database storage. However, upon submission, the page redirects to submit.php instead of staying on the current page. How can I make it submit without ...

Unable to generate JSON format using PHP's json_encode function

When utilizing the following code snippet: $data = array(); $sql = "SELECT * FROM list"; $result = $db->query($sql); if ($result->num_rows > 0) { while($row = $result->fetch_assoc()) { $data['title'] = $row['titl ...

Randomly undefined custom jQuery function

Appreciate your assistance in advance. I am facing a peculiar scope issue on a page where multiple charts are rendered intermittently. I have created a set of jQuery functions to display different types of charts based on the provided options. Each funct ...

Displaying the array after input from the user has been loaded

Is there a way to capture user input from an HTML form and store it in an array using javascript? I want to then display the array as a list in a div tag in the HTML. Although my code is functioning, it seems to be outputting the text twice instead of jus ...

Leverage information from ng-repeat to interact with @ajax.actionlink

Looking to dynamically load data into an @ajax.actionlink <tr ng-repeat="child in row.child" ng-if="row.visible" class="expand-wrapper"> <td> @Ajax.ActionLink("{{child.contractname}}", "home", "index", new ...

Manipulate the CSS style of the body element in Angular with Typescript using the important tag

Within my Angular application I have implemented the following code to customize the body style: constructor(private elementRef: ElementRef) { } ngOnInit() { this.elementRef.nativeElement.ownerDocument.body.style.overflowY = 'hidden'; ...

Is there a way for ASP.NET MVC to automatically notify when a record is edited or updated?

Having recently used the NotifyIcon class in a windows application, I found it to be quite useful. As someone who primarily works as a web developer, I am curious if there is something similar available for websites. The website that I am working on inclu ...

effectively showcasing information in a datatable by converting JSON data into objects

I am looking for a way to display balance information in datatables, but I have not been able to find a solution yet. <!DOCTYPE html> <html lang="en"> <head> <title>Comment</title> <meta charset="u ...

Having trouble getting jQuery .append() to behave the way you want?

I have created a code snippet to display a table like this: $("#results").append("<table><tr><th>Name</th><th>Phone Number</th></tr>"); $("#results").append("<tr><td>John</td><td>123123123 ...

Protractor will pause for 30 seconds once the page has finished loading in Angular 2

I'm currently working on creating my first end-to-end tests for an Angular 2/4 application using Protractor. So far, everything is running smoothly as the pages load and input fields are successfully filled. However, I've encountered a major iss ...

Is there a way to identify when an element falls outside the bounds of a circle?

I have implemented a feature using the raphael.js library that involves creating a circle with a small black circle inside it. The goal now is to drag this small circle out of the larger one. How can I determine whether the small circle was dropped outsi ...

There was an issue encountered when attempting to access the stackoverflow api

I am currently attempting to retrieve all questions tagged with ipv4 from stackoverflow using the stackoverflow API. However, I encountered the following error message: No 'Access-Control-Allow-Origin' header is present on the requested resource. ...

ng-repeat dysregulating the binding of directive models

<input-directive model="config.shared.product.whatevers[0]"></input-directive> <!-- This code is functioning correctly, however the following does not bind properly --> <td ng-repeat="whatever in config.shared.product.whatevers trac ...

Display or conceal a frame with the help of JavaScript or jQuery

Is there a simple way to hide the "topFrame" and "menu" frames when clicking an image or button, and then unhide them by clicking again? Apologies for not including the "topFrame" and "menu" jsp files, as they are dynamically generated in my application. ...

TypeScript Compile Error: The property is not available in the 'IStateParamsService' type

My client project heavily utilizes TypeScript. Currently, I am encountering a technical issue. Within my HTML code, I have an anchor tag as shown below: <a class="btn btn-default mrm" ui-sref="course-detail({courseId: '{{c.Id}}'})">Detail ...

ability to reach the sub-element dictionaries in typescript

class ProvinciaComponent extends CatalogoGenerico implements OnInit, AfterViewInit { page: Page = new Page({sort: {field: 'description', dir: 'asc'}}); dataSource: ProvinciaDataSource; columns = ['codprovi ...

Is there a way to sort through a JSON object array with jq?

I have made significant progress. json input, 'data.json': [ { "Selected": null, "Family Name": "Jones", "Couple Name": "Jones, Adam & Rachael Margaret", "Family Phone": "404-4477", "Family Email": "<a href="/cdn-cg ...

AngularJS disrupts the JSON data format

Upon receiving data from the server in JSON format, I have noticed that it is not displaying in the expected order: [{ "outlet_id": 83, "outlet_name": "My Outlet", "address": "My Outlet", "shop_number": "123", "street": "123", "building_no": ...