Preserving arrays and objects inside the specified array

I am currently working on developing a simple to-do app with vue.js. My goal is to save the to-dos stored in an array so that they persist even after resetting the site. After browsing through some documentation, I came across the following solution:

data() {
        return {
            array: [
                 {id: 1, label: 'learn vuejs'},
            ]
        }
    }, 
methods: {
        persist() {
            localStorage.array = this.array;
            alert('items saved')
        }
    },
mounted() {
        if (localStorage.array && localStorage.array.id) {
            this.array = localStorage.array;
            this.array[id] = localStorage.array.id;
        }
    },

Although this code successfully saves the array to localStorage, it fails to capture the objects within the array. Upon checking localStorage in the console, the output is as follows:

array: "[object Object]"

If anyone has a solution to saving the items within the array, please provide detailed instructions.

Answer №1

Ensure that you save them as strings. For example, use

localStorage.array = JSON.stringify(this.array)
. When retrieving from localStorage, you can decode it using
this.array = JSON.parse(localStorage.array);

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 style display:none not functioning in IE8, IE9, and IE10 when in Compatibility View mode

I am facing an issue with two DIVs on my webpage. One of them is set to have display:none based on certain conditions. Surprisingly, it works perfectly fine on IE10, Firefox, and Chrome. However, the problem arises on IE8, IE9, and IE10 Compatibility Vie ...

Growler and ES6Code

My project uses a Grunt compiler along with jshint for validation. When working with multiline strings, I typically use the following syntax: string = '` Hello `'; However, upon compiling, I encounter the following error: [L328:C33] ...

The javascript file is unable to detect the presence of the other file

I am facing an issue with two JavaScript files I have. The first one contains Vue code, while the other one includes a data array where I created the 'Feed' array. However, when trying to output a simple string from that array, the console throws ...

Create a hierarchical dictionary structure by nesting dictionaries containing child elements from an array

Let's say I have fetched an array of dicts from a web API. Each dict contains keys like name, description, 'parent', and children. The children key consists of an array of dicts. Here is a hypothetical example for better understanding: [ ...

JavaScript function failing to utilize innerHTML output

Having trouble with my BMI calculator code. Even after adding sample text for testing in JavaScript, the function still isn't working. Can someone help me figure out what's wrong? <h2>Welcome to BMI calculator</h2> <h4>Please ...

In what scenarios is it ideal to utilize jQuery.each() over _.each() from Underscore? Conversely, when would _.each() be more suitable than jQuery.each()?

What are the specific situations where it is more appropriate to use jQuery.each() rather than _.each()? When would you recommend using _.each() over jQuery.each()? If you have any suggestions, please share them. ...

Retrieve a variable from the context and assign it to the Angular scope

I'm having trouble accessing the sourcePath in the controller $scope. This is the code I have: (function() { var sourcePath; sourcePath = 'app/assets/javascripts/shared/controllers/some_controller.coffee'; angular.module("shared"). ...

A streamline method for creating nested tables using Jquery

I've developed the following code snippet that generates a table within another table based on JSON response data. Code for Main Table var user = '<table width="98%" cellspacing="0" cellpadding="1" style="text-align: left; margin: 0 auto;&a ...

Bootstrap 4: The mystery behind why the popover fails to appear inside a scrollable dropdown

Is there a way to replicate the behavior of Bootstrap 3 dropdowns with scrollbars on hover and popovers in Bootstrap 4? It seems that setting overflow:hidden; for scrolling functionality in dropdown menus also hides the popover. I have tried using containe ...

Unable to access route after authentication - AWS Cloudfront and AWS S3 due to denial

I am facing an issue with my S3 bucket containing a Vue.js application. You can view the content in the following link: S3 bucket content In order to securely deliver this content, I have set up a Cloudfront distribution. To ensure security, I created an ...

json evaluation causing an issue

When trying to use eval for the JSON below, I am encountering a syntax error with the message: Expected ']'. I am unsure of what is missing in my code. Here is my JavaScript statement: eval('var jsonResponse = ('+response+')' ...

In AngularJS, variables can undergo automatic value changes without any external connections

Within my AngularJS controllers, I have initialized two variables: _this.currentData=new Array(); _this.masterCurrentData=new Array(); Later on, I created a temporary array of objects called tmpDataSort and populated it separately using loops. var tmpDa ...

Retrieve a collection containing all the variables that have been defined

I am attempting to gather all PHP defined variables and store them in an array. Previously, I tried: $myArr = get_defined_vars(); var_dump($myArr); The result was: array(4) { ["_GET"]=> array(0) { } ["_POST"]=> array(0) { } ["_COOKIE"]=> array ...

The $multiply function is only compatible with numerical data types, not arrays

Attempting to utilize the $multiply operator within MongoDB. STEP 1 db.message1064sd_00011_3744.aggregate([ {$project : { "prices.00026" : 1, priceReal : { price : "$prices.00026", } }}, { $match : { ...

Unable to install Vue-Cli

Currently running node 11.2.0 Continuously encountering this issue. Andrews-MacBook-Pro:vueTutorial aharris$ npm install -g @vue/cli npm WARN deprecated <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8ee6e1ebe5cebba0bea0ba" ...

Displaying various data sets from data tables created using Ajax on Highcharts

I am currently working on integrating multiple data series into Highcharts' plot. I want to retrieve the data from an ajax self-calling function, which would allow for almost real-time updates to the charts without redrawing the entire chart each time ...

Adding styles dynamically using methods is not supported in Vue.js

When it comes to adding styles to an HTML element from methods, I ran into a small hiccup. Here's what I tried: <div class="add-profile-img" v-bind:style="getBackgroundImg()"> The method in question is: getBackgroundImg: function() { return { ...

Success is returned as AJAX error

My AJAX call is returning an error as Success instead of a JSON error from ASP.NET MVC. Can someone please advise on how I can resolve this issue? Thank you. [HttpPost] public JsonResult Register(int EventID) { try { ...

Python - Incorporating an additional row into an array argument

Looking for a way to add a row of 0 to an array parameter in a function. MNWE : import numpy as np def addrow(A): n,p = A.shape temp = np.zeros((n+1,p)) temp[:n,:] = A A = temp Struggling with defining A as a local variable and raising a ...

What is the process for dynamically checking in a node in jstree?

I am utilizing Jstree from https://github.com/vakata/jstree. I have successfully loaded the tree structure, and now I want to bind checked checkboxes from an array of data. By default, the nodes have unique ids. I will check the id of each node in the arra ...