Storing an array of objects in local storage is not working in Angular 9

I've encountered an issue trying to save an array of JSON objects into local storage, and I'm puzzled as to why it's not functioning correctly. Despite utilizing

localStorage.setItem('comparisons', JSON.stringify(setComparisons))
, nothing appears to be stored for some unknown reason.

The array I am attempting to store contains the necessary information since everything shows up when I log the array in the console prior to saving it.

In the past, I've successfully stored similar objects (albeit not arrays of these objects) in localStorage and retrieved them without any obstacles. However, I cannot pinpoint whether the problem lies with this being an array nested within arrays of arrays or something else entirely.

Below is the code snippet:

import { Component, OnDestroy, OnInit, ElementRef } from '@angular/core';

import * as jasmineData from '../../../../assets/data/jasmine.json';
import * as belleData from '../../../../assets/data/belle.json';
import * as trumpData from '../../../../assets/data/trump.json';
import * as katyPerryData from '../../../../assets/data/katyPerry.json';
import * as snoopDogData from '../../../../assets/data/snoopDog.json';

@Component({
  selector: 'ngx-header',
  styleUrls: ['./header.component.scss'],
  templateUrl: './header.component.html',
})


export class HeaderComponent implements OnInit, OnDestroy {
 
 constructor(){}
 
 ngOnInit(){

    if(localStorage.getItem('comparisons')){

      console.log("localStorage 'comparisons', set to: " + JSON.parse(localStorage.getItem('comparisons')))

      let testOutput = JSON.parse(localStorage.getItem('comparisons')) 

      console.log(testOutput) //<<<<< outputs nothing

    }
    else{

      let setComparisons = []

      setComparisons['jasmine'] = jasmineData['default']
      setComparisons['belle'] = belleData['default']
      setComparisons['trump'] = trumpData['default']
      setComparisons['katyPerry'] = katyPerryData['default']
      setComparisons['snoopDog'] = snoopDogData['default']

      console.log(setComparisons) //<<<<<<<<<< this works
 
      localStorage.setItem('comparisons', JSON.stringify(setComparisons)) //<<<<<<<<<<<< this doesn't work

    }
 }

Furthermore, here is an example of one of the JSON objects inside the array:

trumpData['default'] = ... (The content has been truncated for brevity)

I sincerely appreciate your assistance!

Answer №1

When initializing an array, make sure to use either actual object or an array with numeric indices:

const setComparisons = {
  jasmine: jasmineData['default'],
  // etc
};

or

const setComparisons = [
  jasmineData['default'],
  // etc
];

Your setData and getData functions can remain unchanged.

The issue with using string keys is that the native toJSON method on arrays only considers the items in the array, not any other properties present on the object. This method is invoked when the object is being converted to a string.

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

Creating a C# program with a JSON file integration

As a newcomer to C#, I am unsure of how to handle JSON files. I would like my script to be able to search for a specific JSON file on my website, but I am lost when it comes to creating a class that can interact with the file. Here is an example of my JSON ...

An improved method for implementing conditional statements in Angular

After researching online, I came across some discussions about using if else logic in Angular. Although I was able to achieve the desired outcome, I am curious if there is a more efficient or alternative way to implement if else statements in Angular. In ...

We are currently moving up from NG 12 to NG 16 and encountering an issue with the package "@ng-bootstrap/ng-bootstrap" due to an incompatible peer dependency

When attempting to upgrade from Angular version 12 to version 13, we encountered some dependency errors. Following the instructions at https://update.angular.io/?v=12.0-13.0, we tried running ng update @angular/core@13 @angular/cli@13. We received the fo ...

Utilizing Retrofit for parsing JSON data of this nature

Looking to utilize the retrofit library for parsing this particular data format. Json { slots” { “123”: [ { “an”: ”yy” “pa”:”ya” }, { “an”: ”s ...

When you extend the BaseRequestOptions, the injected dependency becomes unspecified

Implementing a custom feature, I have chosen to extend BaseRequestOptions in Angular2 to incorporate headers for every request. Additionally, I have introduced a Config class that offers key/value pairs specific to the domain, which must be injected into m ...

Strategies for enhancing the effectiveness of a try statement when repeatedly used in Python

I am currently working on extracting various elements from a JSON object that consists of metadata related to a specific song using Python. In order to verify the availability of information, I have implemented try-except statements for each metadata eleme ...

"Performing a series of getJSON requests with a delay between each call, iterating through an array

Could someone shed light on why my jQuery/JavaScript code runs with an unexpected flurry of ajax calls instead of at a steady 1-per-second rhythm? var i = 0, l = data.length; function geocode() { $.getJSON( 'https://maps.googleapis.com/maps/api ...

Steps for displaying a 404 page on a server-side rendered dynamic route following a client-side page transition

I'm currently developing a next.js project using Contentful as the Content Management System. My goal is to display a 404 page for a server-side rendered dynamic route after a client-side page transition. When I directly request the page (by entering ...

Utilizing a single route guard for multiple routes with varying authorization requirements

In my Angular 6 project, I currently have an canActivate AuthGuard that is set up to load ComponentA. Now, I am wondering if it's possible to reuse the same AuthGuard for Component B, even though the authorization logic for Component B is completely ...

When running the command `npm audit fix --force`, an error is triggered stating that the data path ".builders['app-shell']" must contain the mandatory property 'class'

After installing a package, I received the following message: added 1 package from 8 contributors and audited 49729 packages in 23.754s found 25 vulnerabilities (1 low, 24 high) run `npm audit fix` to fix them, or `npm audit` for details I proceeded to ...

What is the best way to transfer an array of intricate objects to a different page in PHP?

In my code, I am working with an array called $batchRequest which has a structure like this: array(5) { [0]=> array(0) { } [1]=> object(Facebook\FacebookRequest)#18 (9) { ["app":protected]=> object(Facebook\FacebookApp ...

How can I make a button change color dynamically in Angular when using Ionic?

<ion-col col-3> <button ion-button (click)="onPunchPress($event)"><span>1</span></button> </ion-col> <ion-col col-3> <button ion-button (click)="onPunchPre ...

The issue of Ajax failing to send POST variables to a specified URL

I'm looking to dynamically populate related dropdowns with data fetched from the database. On my HTML page, I have a select element with the id 'fontes' and another one with the id 'cargos'. Below is the jQuery code snippet that I ...

Guide on creating a Jasmine test for a printer utility

Currently, I am working on writing a Jasmine test for the print function shown below: printContent( contentName: string ) { this._console.Information( `${this.codeName}.printContent: ${contentName}`) let printContents = document.getElementById( c ...

Retrieving the image field value using FSS in Plone 3.x

I am currently in the process of transferring an older Plone 3.3 website that utilizes FileSystemStorage with the help of Mikko's Simple JSON export script. Everything seems to be working smoothly, with the exception of missing values in the image fi ...

How to modify a record in an array within MongoDB by leveraging webMethods

I need to find a specific document in an arrayList, with the following JSON string: { "_id" : ObjectId("58b9339502be203f6b476664"), "_docType" : "Test", "type" : "mongoUpdate", "createdDateTime" : "2017-03-03 09:12:53.080", "contacts" : [ ...

Issue with TypeScript: Declaring type for objects in an array using .map

I'm having trouble assigning types to the Item object that is being returned from unitedStates.map((item: Item) => {}. Despite my efforts, I am unable to correctly define the types. Although I have specified the unitedStates array of objects as un ...

The value of "metadata" is not a valid export entry for Next.js

After I installed Next.js 14 with TypeScript, I encountered an error related to my metadata type definition. import type { Metadata } from "next"; export const metadata: Metadata = { title: "next app", description: "next app 1 ...

Selecting JSONB keys in a case-insensitive manner in PostgreSQL (version 9.4 and newer)

Configuration (Using PostgreSQL 9.4+) Imagine a scenario where there is a table called product: create table product ( attributes jsonb ); and it contains the following data: insert into product (attributes) values ('{"Color": "Red"}'), ...

The NestJs provider fails to inject and throws an error stating that this.iGalleryRepository.addImage is not a recognized function

I'm currently working on developing a NestJS TypeScript backend application that interacts with MySQL as its database, following the principles of clean architecture. My implementation includes JWT and Authorization features. However, I seem to be enc ...