What is the best way to set up localStorage with a multi-dimensional array

I am struggling with modifying my local storage and it's taking up a lot of my time.

Initially, I set it up like this:

localStorage.setItem('example','{"data": []}');

It was working fine, but now I need to structure it like the following example:

{
    "data" : [
        {
            "id" : "0",
            "name" : "Alice",
            "type" : "A",
            "value" : "1",
            "created_at" : "2012-09-23 08:00:00"
        },
        {
            "id" : "1",
            "name" : "Bob",
            "type" : "B",
            "value" : "5",
            "created_at" : "2012-09-23 10:00:00"
        }
    ],
    "index" : 0
}

So, I tried this:

localStorage.setItem('example','{"data":[]},{"index":0}');

But now I keep getting the error message:

SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data
[Break On This Error]   

var objJSON = JSON.parse(localStorage.getItem('example'));

Can someone help me understand how to correctly initialize my local storage? Thanks.

Answer №1

To implement this design pattern, you can utilize JSON stringify to serialize the object that needs to be stored. Here is an example:

let objectToStore = {
  components : [
    {
        "id" : "1",
        "name" : "Tom",
        "type" : "camera",
        "size" : "small",
        "color" : "red",
        "created" : "2020-05-15 10:30:00",
        "modified" : "11:00:00",
        "status" : "active"
    }]
};
localStorage.setItem('exampleData', JSON.stringify(objectToStore));

Answer №2

It looks like you have multiple objects there. If that's what you need, make sure to use square brackets for an array:

localStorage.setItem('bipme','{"modules":[]},{"modulesIndex":0},{"watchPosition":[]}');
// Instead, it should be:
localStorage.setItem('bipme','[{"modules":[]},{"modulesIndex":0},{"watchPosition":[]}]');

If you want modulesIndex and the others to be part of the same object, then simply don't close the object:

localStorage.setItem('bipme','{"modules":[],"modulesIndex":0,"watchPosition":[]}');

It seems like you already figured this out based on your comment.

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

Manipulating CSS rules using JavaScript/jQuery

My goal is to create a function that generates a grid based on table data. While the function itself seems to be working, I am encountering an issue where the classes applied are not resulting in any style changes. Below is a snippet of my function: $(doc ...

The onChange event will not be triggered in an input component that is not intended to be uncontrolled

Could someone please assist me in understanding why the onChange event is not being triggered? I am customizing ChakraUI's Input component to retrieve a value from localStorage if it exists. The component successfully retrieves the value from localS ...

Having issues with the latest version of Fabric JS code running properly

Hello, I stumbled upon this JS fiddle (http://jsfiddle.net/efmbrm4v/2/) and I really need something similar to function properly. The fiddle uses an older version of fabric js (1.4.0) and I'm having trouble getting it to work with the newer versions ( ...

Tips for updating the value of a key in a JavaScript object when the TextField tag's value changes

Here is the schema I am using for my model: const workoutSchema = mongoose.Schema({ workouts: [ { workoutName: String, sets: Number, reps: Number, weight: Number, }, ], }); Below is the postData referenced in the text f ...

I am facing an issue where adjusting the width of an iframe based on the browser using jquery is not

Having an issue with setting the height and width of a div and iframe based on browser window size using the following code: var newheight = $(document).height(); var newH = parseInt(newheight) - 170; var newHI = parseInt(newheight) - 215; ...

Using Node.js and Express to retrieve data from a MySQL database and update a table

My .ejs file contains a form that sends data to a MySQL database and then displays two tables with the retrieved data on the same page. However, I am facing an issue where the tables do not refresh after submitting the form, requiring me to restart the ser ...

Inquiry about how TypeScript handles object property references when passed into functions

As a newcomer to TypeScript, I am exploring the creation of a range slider with dual handles using D3.js. I have developed a simple class for managing the slider objects: export class VerticalRangeSlider{ private sliderContainer: d3.Selection<SVGG ...

Designing an architecture for a Java, Android, and database application - what will the final app's appearance be

I am currently working on a website where users need to complete tasks using an Android device: Fill out a simple HTML document. Sign the document on their Android device. Save the data entered into a database on the website. Some key points to consider ...

Expressing the relationship between API endpoints in a nested structure

I'm currently working on a REST API using expressjs. There are two api endpoints that I have defined: router.get('/probe/:id', function() {}); router.get('/:id', function() {}); However, I am facing an issue where calling the fir ...

reasons for utilizing `this.initialState = this.state;`

Could someone help me understand why I am using this.initialState in a React JS class component setup? class Registration extends Component { constructor(props) { super(props); this.state = { username: '', email: '&apo ...

The `this` keyword is incapable of accessing the object. It is instead pointing to the `window` object

Here is a sample of Javascript constructor code: function TestEngine() { this.id='Foo'; } TestEngine.prototype.fooBar = function() { this.id='bar'; return true; } TestEngine.prototype.start = function() { this.fooBar( ...

Database hosted on Heroku platform

Curious to know, if you utilize Heroku for hosting, what database do you prefer? Do you lean towards PostgreSql, MongoDB, or another option altogether? I initially developed a bot using sqlite3, but quickly discovered that Heroku does not support it and ...

Generating a highchart by retrieving JSON data using AJAX

I'm currently working on generating a basic chart on a webpage using data from a MySQL database that is fetched via a MySQL script. My main challenge lies in understanding how to combine the ajax call with the necessary data for the chart. I'm n ...

Optimal row settings for different reports using Material-UI table pagination

Recently, I've been exploring an example involving material-ui's TablePagination. In this scenario, they present a useTable component with the following code snippet: import React, { useState } from 'react' import { Table, TableHead, Ta ...

User input determines the path of Iron Route in Meteor

A requirement is to execute a function that prompts the user for input and then navigates to that specified value. For instance, if the inserted value is: https://www.youtube.com/watch?v=_ZiN_NqT-Us The intended destination URL should be: download?u ...

What is the best method to incorporate extra parameters into highcharts using data extracted from datatables?

I have a query regarding the integration of datatables with highcharts. The issue I'm facing is related to specific configurations for chart-A, which is of column type. Even after applying the configurations, it seems like they are not being incorpora ...

Can you please tell me the CSS pseudo element that corresponds to the AM/PM field in an <input type="time">

The issue with the am/pm display is dependent on the browser that the app is opened in. I am looking for a universal solution to ensure it does not appear in any popular browsers. Below is the HTML code for my input time field: <input type="time" for ...

Prevent title flickering in Android using Ionic

I am attempting to create a tab content page using the "standard" method recommended by the ionic template example. However, I have noticed that when switching between tabs on Android, the view title flickers. This issue is not present on iOS or desktop b ...

Challenges with Asset Management in Vite Compilation Result

I'm encountering a problem with structuring assets in the output directory while utilizing Vite for my project. I have set up the output.assetFileNames option to categorize assets into subfolders based on their types (css, fonts, img, js), but it&apos ...

Encountering an error message when trying to launch an application: Module

Every time I try to launch my react-native app in git-bash, I encounter the following error message. I have already uninstalled and reinstalled node.js, cleared the cache, and attempted various solutions from Stack Overflow and GitHub with no success. ...