Storing and accessing JavaScript arrays in a local JSON file

I am working on a school project and any assistance would be greatly appreciated.

Upon execution in a browser like Chrome, the array below gets populated with data.

I am trying to determine how to store or update this array in a local file.

var listDataObject = {
  reminderListArray: [{
      title: "Sample one",
      star: true,
      checkbox: true
    },
    {
      title: "Sample two",
      star: false,
      checkbox: false
    }
  ]
};

In theory, I know that I need to convert the array into JSON format and then save it to a file.

I have also read about parsing the JSON data when retrieving it.

However, this is as far as I have progressed.

saveText(JSON.stringify(listDataObject), "filename.json");

function saveText(text, filename) {
  var a = document.createElement('a');
  a.setAttribute('href', 'data:text/plain;charset=utf-u,' + encodeURIComponent(text));
  a.setAttribute('download', filename);
  a.click();
}

For your reference, here is the complete script:

...

Answer №1

To utilize the current local Storage space, you can create a Storage object by using window.LocalStorage along with the getItem and setItem methods. When dealing with an array of objects like remainderListArray, there's no need to stringify listDataObjects or enclose remainderListArray within ListDataObjects since it can be parsed as JSON and retrieved into an array directly from local storage. Therefore, removing listDataObjects in this context would be beneficial.

    var dataObjects = [];

    for(var i = 0; i < remainderListArray.length; i++) {
        dataObjects.push(remainderListArray[i]);
    }

    // Convert the dataObjects array to a string and store it in local storage
    localStorage.setItem('dataObjects', JSON.stringify(dataObjects));

When adding a new object:

     // Retrieve the stored dataObjects array in JSON format from localStorage
     var dataObjects = JSON.parse(localStorage.getItem('dataObjects'));
     
     // Add the newDataObject to the dataObjects array
     dataObjects.push(newDataObject);
     
     // Update the dataObjects array in localStorage
     localStorage.setItem('dataObjects', JSON.stringify(dataObjects));

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

Issue with JSONP request in jQuery/AJAX

I am currently attempting to make a request to a different site, which requires authentication through a cookie. Oddly enough, when I try making the call like this : $.getJSON(url + '?', function(data){ alert(data); }); The HTTP headers do ...

Is it possible to trigger an event just once?

Is there a way to ensure an event only fires once? I recently discovered that using .one seems to do the trick. ...

The Autocomplete component from MUI is alerting me to provide a unique key for every child element being passed

I am currently using the Autocomplete component from MUI and encountering an issue with a warning that says: Warning: Each child in a list should have a unique "key" prop. Although I've added keys to both renderOption and renderTags, the wa ...

The type 'number' cannot be assigned to the type 'Element'

Currently, I am developing a custom hook called useArray in React with TypeScript. This hook handles array methods such as push, update, remove, etc. It works perfectly fine in JavaScript, but encounters errors in TypeScript. Below is the snippet of code f ...

Is the accuracy of the in-situ convolution filter guaranteed?

After analyzing my simple box blur function, I have come to the realization that it may be incorrect. The current implementation edits the ImageData object in place, leading to convolution filters depending on surrounding pixels that have already been ch ...

Generate a Calendar Table using JavaScript in the Document Object Model (DOM

I have set up a table with 6 rows and 5 columns. The purpose of the table is to represent each month, which may have varying numbers of days. I want each column to display dates ranging from 1-30 or 1-31, depending on the specific month. Here's what ...

Manipulating the state of the <audio> HTML5 element with Javascript

Are there any Javascript methods available to retrieve information about the current state of an audio tag? For example: Is the audio playing? Has it stopped? Is it muted? Is it paused? I am aware of using play(), pause(), and others, but I'm unsure ...

Tips for swapping out a div tag with another div tag in the same spot without needing to redirect to a different page by utilizing bootstrap

Currently, I am developing a JSP project that utilizes Bootstrap for the frontend. I have come across a question regarding HTML design. Is there a way to replace one div tag with another div on the same page without navigating to a new URL using Bootstrap ...

Multer's re.file function is returning an undefined value

I am seeking assistance with my coding project. I have a setup that uses React on the front end, Node.js on the backend, and MySQL as the database. The issue I am facing is related to file transfer using Multer in Node.js. When trying to transfer files, Mu ...

Display additional inputs using the PHP Foreach Loop depending on the selection made

I have a PHP Foreach loop that includes a "Quantity" input field. When users select a quantity, the corresponding number of new inputs should be displayed. For example, if the user chooses a quantity of "3", then 3 new inputs should appear for that item. K ...

Using nodeJS to showcase content on a web page

I'm relatively new to NodeJS, and I am trying to figure out if there is a way to utilize NodeJS similar to JavaScript. My goal is to retrieve data from a database and display it within a div on my index.html page. When attempting to use querySelector, ...

Generating PDF files from HTML documents using Angular

I am currently working on an Angular 11 application and I have a specific requirement to download a PDF file from a given HTML content. The challenge is that the HTML content exists independent of my Angular app and looks something like this: < ...

Error on Network: 400 BAD REQUEST in Ionic framework

I recently implemented push notifications successfully, but I am facing a network error with a 400 bad request when trying to access a specific API endpoint. The error message states: "NetworkError: 400 BAD REQUEST - https://apps.ionic.io/api/v1/app/77c3 ...

Executing JavaScript code from an external HTML file

My goal is to create and utilize native web components by defining them as HTML files containing markup, CSS, and Javascript all bundled together in one file, similar to how Vue handles .vue files. These components would be fetched from an external compone ...

Storing external API requests in create-react-app's service worker for faster retrieval

I'm in the process of transforming a React web application into a PWA (Progressive Web App). I've made the necessary change in the index.js file - serviceWorker.register();. Everything is functioning properly as I can access the home page and as ...

The issue of the Angular 4 double click event not functioning properly on mobile devices

I have implemented a double click functionality in my code, which is working perfectly in desktop view. However, I am facing an issue when switching to mobile or tablet view as the double tap feature does not work. Below is a snippet of my code: HTML: & ...

Comparison of Grant and Passport.js: Which One to Choose?

Are you unsure about the distinctions between Grant and Passport.js? How do you decide when to utilize Grant over passport.js, and vice versa? If your goal is to create a social media platform that tracks user activities and posts them on a news feed, whi ...

Issues with data-ng-click functionality in AngularJS combined with UI Bootstrap and MVC Frontend

I am encountering difficulties while attempting to register a user by fetching data from form inputs on the frontend and sending it to the backend using AngularJS. Below is my index.html file: <!DOCTYPE html> <html data-ng-app="collectionsApp"&g ...

Mongoose - run a function on a designated date within the document

Currently, I am developing a cryptocurrency-based betting game project. My database of choice is mongodb and I utilize mongoose for interaction with it. Within this database, I have a collection that houses documents detailing various betting games. Each d ...

Looking to create dynamic pages on NextJS without relying on fixed paths?

I am looking to create a unique user experience by offering discounts on my website based on the users' citizenship ID numbers. By using their ID number, I can customize the discount amount according to factors such as location, age, and gender. User ...