Is it better to store data individually in localStorage or combine it into one big string?

When it comes to keeping track of multiple tallies in localStorage, one question arises: Is it more efficient to store and retrieve several small data points individually or as one larger chunk?

For example:

localStorage.setItem('id1', tally1);
localStorage.setItem('id2', tally2);

for(var i=0; i<tallyIds.length; i++){
    this.tallies.push(tallyIds[i], localStorage.getItem(tallyIds[i]));
}

Or consider this approach:

localStorage.setItem('tallies', '[{"id1": tally1}, {"id2": tally2}"]');
this.tallies = JSON.parse(localStorage.getItem('tallies'));

While storing each tally separately may prevent the loss of all data if some is cleared by the device periodically, consolidating them into a single string could result in losing everything at once. However, would looping through a few hundred items significantly slow down the process?

Answer №1

To optimize efficiency, it is strongly recommended to save the tallies as an array under a single key in localStorage. If localStorage is ever cleared, individually storing the tallies:

a. is not guaranteed to retain any of them (using localStorage.clear(), for example, will remove everything) b. may result in uncertainty regarding the integrity of your data - are all tallies intact or have some been lost?

Furthermore, by saving the tallies as an array, you gain the flexibility to easily perform operations such as filtering, mapping, sorting, and reversing them.

Answer №2

To simplify your situation, you may find it more convenient to store all the tallies in a single localStorage key and value (as a combined string) and utilize JSON parse for reconstructing your object. This way, you can easily add to it and then stringify it again, rather than dividing the data into separate keys for each tally.

If your data structure is not too complex and does not require a full-fledged local database like IndexedDB, using a single key with a JSON string value should suffice.

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

The ESLint setup specified in the package.json file for eslint-config-react-app is deemed to be incorrect

The property named "overrides" has the incorrect type (expected array but received {"files":["**/*.ts","**/*.tsx"],"parser":"@typescript-eslint/parser","parserOptions":{"ecmaVersion":2018,"sourceType":"module","ecmaFeatures":{"jsx":true},"warnOnUnsupported ...

Using Jquery to duplicate a row from one table and insert it into another table

Recently, I've dived into the world of jQuery and JavaScript with the goal of creating a simple app. The main functionality I'm trying to implement is the ability to copy a row from one table to another and then delete the original row when a but ...

Exploring the principles of object-oriented design within the context of Node

I am facing challenges with the asynchronous flow of Node.js. Let's assume we have the following class: function myClass() { var property = 'something'; var hasConnected = false; this.connect = function(params) { // Logic to conn ...

What is the best way to display the arrows on a sorted table based on the sorting order in Angular?

I need assistance with sorting a table either from largest to smallest or alphabetically. Here is the HTML code of the section I'm trying to sort: <tr> <th scope="col" [appSort]="dataList" data-order ...

Having trouble with implementing both filter and infinite scroll simultaneously in an Ionic list?

I've encountered an issue with my ionic hybrid app related to angularjs filters. The code snippet below showcases the problem: <input type="search" placeholder="Search personalities" ng-model="name" ng-change='alert("changed!")&apo ...

Passing a variable through jQuery onClick event to a URL via GET request and subsequently loading the content of

After successfully passing variables through AJAX calls via onClick to a PHP file and loading the results on the initial page, I now face the challenge of passing a variable analogously via onClick to a PHP file but this time I need to either open a new wi ...

Tips for creating a binding between an HTTP service and a variable in AngularJS that adjusts when the server data is modified

Using an http get request in angular to extract data into an object with the users currently connected to my app requires refreshing the information every time for binding to the scope. To achieve this, I implemented a method to refresh the data from the a ...

Clickable div containing a hyperlink

I need assistance with a clickable div that contains a link. Here is the setup: HTML: <div onClick="goToCat(2);" class="author-topics-block "> <a href="http://mywebsite/page/?cat=2">The woman in steel</a> </div> CSS: .author ...

"Unraveling Vue.js: A guide to fetching JSON data one object at a time

I am facing a challenge with a large JSON file (40 MB) that includes data on countries, their IDs, and a total sum that I need to calculate. { "0": { "id": 0, "country": "usa", "sum": 201, }, ...

The value within the style.setProperty function does not get applied

I have a progress bar that dynamically increases based on user input: <div class="progressBarContainer percentBar"> <div class="progressBarPercent" style="--width:${gPercent}" id="${gName}-pbar">< ...

How can you automatically show the current time upon entering a page using React Native?

Is there a way to automatically display the current time when a user enters the page? I currently have code that only shows the current time when the TouchableOpacity is pressed, but I want it to update automatically as soon as the user arrives on the Ne ...

Encountering an error in React when attempting to convert a class component to a function

As I've been converting my class components to functions, I encountered a hook error related to my export default. Although I believe it's a simple issue, I can't seem to find the solution I need. The following code is where the error occur ...

To ascertain whether the mouse is still lingering over the menu

I have a condensed menu construction that unfortunately cannot be changed in HTML, only CSS and JS modifications are possible! $('span').on("hover", handleHover('span')); function handleHover(e) { $(e).on({ mouse ...

Transitioning React Hover Navbar Design

I'm currently revamping a click-to-open navbar into a hover bar for a new project. I have successfully implemented the onMouseEnter and onMouseLeave functions, allowing the navbar to open and close on mouse hover. However, I am facing an issue with ad ...

Decoding the information received from Socket.IO within the Flash client

When utilizing server node.js and module Socket.IO, data transmission is handled as shown below: var tests = [555, 777]; client.send("Test string"); //first message client.send({tests:tests}); //second message If the data sent is a text string (fi ...

Utilizing markModified inside a mongoose class that does not inherit from mongoose.Document

In my Typescript code using mongoose ODM, I am implementing a simple queue structure. The challenge arises when directly mutating an array instead of assigning a new value to it because mongoose doesn't automatically recognize the change. To resolve t ...

A custom script developed to detect the presence of the numeric combination "11" and promptly notify the

I am attempting to develop a unique chrome extension that detects typing errors in orders. For example, if the user accidentally types "11" instead of "1", an alert should be triggered. However, I am encountering an issue where the script is running in an ...

Custom styling options for Google Chart

I have been attempting to dynamically adjust the width and height of a google-chart directive by utilizing input field values. However, I am encountering an issue where the width and height are not updating as expected. Check out the Plunker here $scope. ...

Navigating through error messages in NextJs 14 can be tricky, especially when faced with the dreaded "ReferenceError: document not defined" or "prerendering error". It's vital to pinpoint exactly which page

When attempting to run the build on my Next.js application, I encountered an error message that is not very informative given the number of files/pages in my project. How can I pinpoint the exact location of this error and determine the root cause? The pro ...

Tips for deactivating a single edit button

Is there a way to make it so that when I click on a checkbox, only that specific todo's edit button is disabled? Currently, clicking on a checkbox disables all edit buttons in the todo list. Any suggestions? class App extends Component { state ...