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!