Storing nested objects in Angular's local storageAnswering the question on how

Is there a way to specify when setting local storage, to add an object inside the existing object?

.ts

export function retrieveFromLocalStorage<T>(storageKey: string): T {
    return JSON.parse(localStorage.getItem(storageKey));
}

export const saveToLocalStorage = (storageKey: string, key: string, value: any) =>
    localStorage.setItem(storageKey, JSON.stringify({
        ...retrieveFromLocalStorage(storageKey),
        [key]: value
    }));
    
saveToLocalStorage('myObj', 'personalInfo', formValuesArray);

This is how it currently stores the value:

"personalInfo":[
      {
         "name":"test",
         "surname":"test2",
      }
   ],

This is how I want it to be stored:

  "personalInfo":{
      "underageChildInfo":[
         {
        "name":"test",
         "surname":"test2",
         }
      ]
   },

Answer №1

Here is a simple JavaScript code that should also function seamlessly in TypeScript:

class YoungPersonDetails{
  constructor(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }
}

class PersonalInformation{
  constructor(youngPersonDetails) {
    this.youngPersonDetails = youngPersonDetails;
  }
}

function execute() {
  var youngPersonDetails = new YoungPersonDetails("Alice", "Johnson");
  var personalInformation = new PersonalInformation(youngPersonDetails);

  localStorage.setItem('personalInformation', JSON.stringify(personalInformation));

  var pi2 = JSON.parse(localStorage.getItem('personalInformation'));

  console.log(pi2.youngPersonDetails.firstName + " " + pi2.youngPersonDetails.lastName);
}

Answer №2

It seems like you are looking to create a dictionary. If that's the case, this reference could be useful:

var items = [{"name": "???"}, {"name": "###"}];
var dictionary = {"personal_data": {"childInfo": ""}}
dictionary["personal_data"]["child_info"] = JSON.stringify(items);
console.log(dictionary)

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

Filtering formArray controls in Angular based on a condition

I'm currently dealing with an issue where I need to filter formArray controls public checklistForm!: FormGroup; this.checklistForm = this.fb.group({ checklistItems: this.fb.array([]) }); // some logic public checklistItems(): FormArray { ...

Issues with the functionality of Angular and Material's multi-level menu and breadcrumb integration

Currently, I am working on a project using Angular 6 and Angular Material 6. I am attempting to create a multilevel menu with breadcrumb functionality. While I have successfully implemented the multilevel menu, I am facing an issue with navigating the menu ...

What is the best way to trigger a useReducer dispatch function from a different file that is not a React component, without relying on Redux?

In my project, I have a function component that shows a game board named "EnemyBoardComponent.tsx" const enemyBoardReducer = (state:number[][], action:Action)=>{ switch(action.type){ case "update": { return EnemyBoard.getGrid(); ...

Double Calling of Angular Subscription

I am currently working with a series of observables that operate in the following sequence: getStyles() --> getPrices() Whenever a config.id is present in the configs array, getStyles() retrieves a style Object for it. This style Object is then passed ...

Guide on utilizing an enum in typescript to establish a default prop value for a react component

I am working with an enum file called Themes.ts export enum Themes { DEFAULT = 'default', DARK = 'dark' } In my <Test/> component, I am trying to use this enum as a default prop. Here is how the component looks: export ty ...

Adding a type declaration to the severity property in React Alert - A guide to Typescript

I've developed a type declaration object for the incoming data, but no matter what I try to define as the type for the property "severity", it's not happy. The options it wants (as displayed below) don't seem feasible. I'm curious if th ...

Sluggish behavior detected in hybrid AngularJS and Angular application when accessed through Safari browser

Lately, I have embarked on the task of migrating an AngularJS application to Angular 4 using the upgrade module. Within my AngularJS directives, I am utilizing a third-party library (ngFlow) for file uploads via XMLHttpRequest.send(). Everything functions ...

Using Typescript: Defining a function parameter that can be either of two interfaces

While browsing through this specific question, I noticed that it was somewhat related to my current issue, although there were notable differences. In my scenario, I have a function named parseScanResults which accepts an object as its argument. This obje ...

Leveraging imported libraries from a parent class is a common practice in Angular

"angular2": "2.0.0-beta.17", How can I import { Http, Response } from 'angular2/http'; in my Base class and use http in the child classes? Is there a way to achieve this? P.S. I'm open to hacks, workarounds, and unconventional solutions. ...

The anticipated data originates from the 'style' attribute, which is formally noted within the 'IntrinsicAttributes & TextInputProps & RefAttributes<TextInput>' type

I have been working on developing a text form using typescript within the React Native framework. To accomplish this, I created a TextInput component specifically designed for email and password inputs. Below is the code I have been working with: TextInpu ...

Javascript's ParseFloat function returns a string instead of a number

I have an array retrieved from an API that looks like this: x = [0, 12.1, 23.45, 100.23, 13.99, 90, 0, 16.1] I need each number to have a decimal point up to two places, such as 0.00 or 12.10. Here is what I tried: x = x.toFixed(x); However, this conv ...

I am struggling to make the map method display the specific components I need

Attempting to create a scalable Custom Form using an array of objects and a custom Input field in a React-Typescript project import React, { ChangeEvent } from "react" import { InputField } from "./InputField" interface FormItem { ...

Hamburger Menu in Bootstrap not functioning as expected

Despite following each step meticulously for implementing the Hamburger menu in the navbar, I encountered an issue. The navbar collapses when resizing the window but fails to open upon clicking it. Below is a sample code snippet for reference. It utilizes ...

Unable to download essential dependencies using NPM

After cloning a repository for a MEAN stack application, the first step was to run npm install. The installation process resulted in: added 1580 packages from 1887 contributors and audited 15249 packages in 281.586s found 18 vulnerabilities (5 low, 12 mod ...

Tips for updating images dynamically in Angular 4

export class AppComponent { title = 'app'; updateImageSource(){ var userInput; userInput = (<HTMLInputElement>document.getElementById('browse1')).value; console.log(userInput); //contains the na ...

Looking for a way to configure webpack with typescript and style loaders for your project template

I recently set up a Vue project using Webpack and typescript, but I ran into some errors when trying to add a <template> element in my .vue file along with a <style> element that caused issues with my webpack watcher displaying errors. Below i ...

Update the TypeScript definitions in the index.d.ts file using the npm command, by overriding it with the reference types

After running npm install, I noticed that the index.d.ts file contains a reference to the wrong path: /// <reference types="[WrongPath]"/>. As someone new to npm, TypeScript, and web development in general, I'm wondering if it's possible t ...

Spartacus storefront is having trouble locating the .d.ts file when using Angular/webpack

Seeking help from the SAP Spartacus team. Encountering errors while developing a Spartacus component, specifically with certain Spartacus .d.ts definition files that cannot be resolved. The issue is reproducible in this Github repository/branch: This pr ...

Discovering the proper way to infer type for tss-react withParams and create

Greetings to everyone and a huge thank you in advance for your generous help. I have a desire to utilize the tss-react library for styling, particularly because I will be implementing Material UI components. As I delve into some documentation, the latest A ...

Use the reduce method to convert a JavaScript object from 2 to 1

Looking to create a function that can transform these objects: const input1 = [ { id: "lkhj68C13h8uWh4RJz7", post: "on XSS attacks", gender: "Littérature", postId: "cxTbP5EZjNCxw7rD60L7", }, { ...