What is the process to convert it into an Array of Objects within Angular 2?

I have been working tirelessly for the past few days to create an Array of Objects that I can store in Local Storage. The main challenge I am facing is retrieving the existing value from Local Storage.

After retrieving the existing array, I need to add the new data object to it. Then, I convert the updated array into JSON format before saving it back to local storage.

onRegisterSubmit(){
    const user = {
        a: this.a,
        b: this.b,
        c: this.c,
        id: Date.now()
    }    

   var abc = [];
   var get =  JSON.parse(localStorage.getItem('user'));
   abc = [get];
   abc.push(user);

   localStorage.setItem('user', JSON.stringify(abc));

   console.log(JSON.stringify(abc));
   console.log(get);
  }

My goal is to have the JSON data structured as an array of objects, similar to the example below,

[{"hour":1,"minute":21,"ampm":"PM","repeatDays":[],"message":"","todayOrTomorrow":"Tomorrow","isRepeatMode":false,"isEnabled":false,"id":"1493797882440"},{"hour":1,"minute":24,"ampm":"PM","repeatDays":[],"message":"","todayOrTomorrow":"Tomorrow","isRepeatMode":false,"isEnabled":false,"id":"1493797896257"},{"hour":6,"minute":14,"ampm":"PM","repeatDays":[],"message":"","todayOrTomorrow":"Tomorrow","isRepeatMode":false,"isEnabled":false,"id":"1493815470408"}]

Here is a snippet of my JSON data.

[[[[[[[{"id":1493820594019},{"id":1493820606448}],{"id":1493820609111}],{"id":1493820610150}],{"id":1493820610553}],{"id":1493820610827}],{"id":1493820611015}],{"id":1493820612018}]

I have been struggling with this for quite some time and would greatly appreciate any help. Thank you!

Answer №1

Each time you make a call, you continue to nest your values in the following manner:

xyz = [retrieve];

Simply update it to:

xyz = retrieve;

and everything should function correctly

Answer №2

var xyz = [];
var userData = JSON.parse(localStorage.getItem('info'));
xyz = [userData];

Instead, you can use the following code:

var xyz = JSON.parse(localStorage.getItem('info')) || [];

Make sure to run localStorage.removeItem('info'); to clear any incorrect data stored by the previous faulty code before implementing the corrected code.

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

Navigating in Angular2 - Altering query parameters on the same page

In my project using Angular 2, I am working on a Component with a datatable that supports paging and sorting. My goal is to update the URL Parameters every time the table page/size and sorting change. When accessing this component via the Router, I also w ...

How to set up 'ng serve' command in Angular to automatically open a private browsing window?

I am looking for a way to open my project in an Incognito Mode browser without storing any cache. Is there a specific Angular CLI flag that can be included in the ng serve -o command or in the Angular CLI configuration file to enable opening a browser in ...

Steps to incorporate padding to a nested Angular Component by leveraging the CSS of its parent component

It is evident from the example at https://material.angular.io/components/expansion/examples that material components can be customized using the CSS of the component embedding them: .example-headers-align .mat-form-field + .mat-form-field { margin-left: ...

React-leaflet with TypeScript is failing to display GeoJSON Points on the map

I am attempting to display points on a map using geojson points in my react application with react-leaflet. However, for some unknown reason, the points are not rendering on the map. When I try importing a JSON file, I encounter an error: TS2322: Ty ...

Error: Unexpected input detected in `ts.resolveTypeReferenceDirective`. This issue may lead to a debug failure

I'm encountering the error below: { "name": "Angular", "version": "1.0.0", ... } If anyone has insights on what steps to take next or the potential cause of the problem, your input would be greatly a ...

Mastering the art of utilizing Function's construct signatures within TypeScript

Currently delving into the TypeScript documentation, specifically exploring More on Functions. However, I find myself perplexed by the code snippet provided below. Can someone offer guidance on how to implement this in practical development scenarios? An ...

Filter out all elements in an array except for one from a JSON response using Angular 2

After receiving a JSON response from a server via HTTP GET, the data structure looks like this: { searchType: "search_1", overview: [ "Bed", "BedSheets", "BedLinen", .. ...

What could be the reason behind TypeScript ignoring a variable's data type?

After declaring a typed variable to hold data fetched from a service, I encountered an issue where the returned data did not match the specified type of the variable. Surprisingly, the variable still accepted the mismatched data. My code snippet is as fol ...

Having trouble uploading a PNG image (logo) with Cypress

I have been attempting to upload a png file using Cypress and here is what I have tried so far: Cypress.Commands.add('upload_image', (fileName, selector) => { return cy.get(selector).then(subject => { return cy.fixture(fileName, &apo ...

Acquire XML documentation for overloaded functions in Typescript

Is it possible for an overloaded function in a subclass to automatically inherit the XML documentation from its base class? When hovering over myFunc I want to be able to see the documentation from the base class when I hover over myFunc, rather than ju ...

Property does not exist when dispatching in React Redux within componentDidMount

Currently, I am navigating my way through my initial project using React + Redux and have hit a few roadblocks while attempting to dispatch a function in the componentDidMount section. I tried to emulate the Reddit API example project from the Redux docume ...

Karma test encounters the absence of a defined Error Zone, causing an issue to

I have been encountering an error while trying to test a service in Angular. The error message reads: An error was thrown in afterAll Uncaught ReferenceError: Zone is not defined ReferenceError: Zone is not defined Despite visiting various forums and ...

Encountering a common issue: Angular 6 and aws-amplify network error issue

I am currently developing an app using Angular 6 and aws-amplify/aws-amplify-angular, where I am attempting to perform a HTTP GET request. However, I keep encountering a generic Error: Network Error message. This error can apparently be caused by various i ...

Creating Custom Form Control with Custom Validation in Angular 6

I designed the app-input component for displaying an input textbox. I am struggling to implement custom form validation. Can you offer any suggestions? ...

Using unicode characters to style your Angular application

Hey there! I have an Angular 5 app on StackBlitz that implements table sorting. You can check it out here: https://stackblitz.com/edit/angular-rxdzom. The code for this app is based on the example from . In the app, I've used a stylesheet at ./app/sor ...

Ways to utilize multiple tsconfig files within VS Code

My project structure in Visual Studio Code is fairly common with a client, server, and shared directory setup: ├── client/ │ ├── tsconfig.json ├── shared/ ├── server/ │ ├── tsconfig.json ├── project.json The tw ...

increase the selected date in an Angular datepicker by 10 days

I have a datepicker value in the following format: `Fri Mar 01 2021 00:00:00 GMT+0530 (India Standard Time)` My goal is to add 60 days to this date. After performing the addition, the updated value appears as: `Fri Apr 29 2021 00:00:00 GMT+0530 (India St ...

Avoiding repetitive logic in both parent and child components in Angular 8

In my parent controller, I have common requests and I also read router params for those requests. However, for the child components, I have different requests but still need to extract the same parameters from the router - resulting in duplicate code. For ...

I am unable to utilize the outcome of a custom hook within a function or within an effect hook

I've developed a unique custom hook that retrieves a list of individuals File: persons.hooks.ts import {useEffect, useState} from "react"; import Person from "../../models/person/Person"; const usePersons = () => { const ...

Custom Angular 2 decorator designed for post-RC4 versions triggers the 'Multiple Components' exception

Currently, I am in the process of updating my Ionic 2 component known as ionic2-autocomplete. This component was initially created for RC.4 and earlier iterations, and now I am working on migrating it to Angular 2 final. One key aspect of the original des ...