What is the best way to capture the inputs' values and store them accurately in my object within localStorage?

Is there a more efficient way to get all the input values ​​and place them in the appropriate location in my object (localStorage) without having to individually retrieve them as shown in the code below?

Below is the function I currently use to update information:

updateContact() {


    if (this.onSubmit()) {

      this.eleveService.apiUpdateEleve(this.token, this.registerForm.get("firstName").value, this.registerForm.get("lastName").value
      ).subscribe((data: any) => {

        // Retrieve form information
        this.student['contact']['us_firstname'] = this.registerForm.get("firstName").value;
        this.student['contact']['us_lastname'] = this.registerForm.get("lastName").value;
        //  this.language = this.student['us_lang'] 
        this.student['us_lang'] = this.lang
        this.translate.use(this.student['us_lang']);

        // Update the object
        localStorage.setItem("student", JSON.stringify(this.student));
        console.log('updated', this.student)
        this.navCtrl.navigateRoot('/e-tabs/explorer');

      })

    }

  }

This is the structure of my Object :

OBJECT :

contact:
country: {id: "BE", name: "Belgium"}
login: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ee828f9d9aae828f9d9ac08c8b">[email protected]</a>"
newsletter: "1"
prest_feedback: "1"
us_address: "Rue des polders 13"
us_city: "Uccle"
us_email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="dfabbaacab9fabbaacabf1bdba">[email protected]</a>"
us_firstname: "Munir"
us_gsm: "0485001128"
us_id: "5c9b35d8b4dd1"
us_lang: "fr"
us_lastname: "Nahman"
us_zip: "1180"
[Object][1]
[Front-end of the page][2]


  [1]: https://i.sstatic.net/SmxSZ.jpg
  [2]: https://i.sstatic.net/oknZd.jpg

Answer β„–1

var student = {
   information: {
    name: "hello",
    class: "hello",
    age: "hello",
    gender: "hello",
    number: "hello",
    username: "hello",
    email: "hello",
    home: "hello",
    mobile: "hello"
   }
};

for ( var detail in student.information ) {
  console.log(detail , student.information[detail])
}

This method enables you to access property names and their corresponding values, allowing for further manipulation as needed.

for ( var detail in this.student.information ) { 
    this.student['information'][detail] = this.registerForm.get(detail).value;
}

Answer β„–2

To efficiently store key-value pairs, consider stringifying the entire object and saving it in your localStorage.

localStorage.setItem('contactObject', JSON.stringify(yourObject));

Retrieving the object from localStorage is as simple as parsing it back into an object.

const retreivedContactObject = JSON.parse(localStorage.getItem('contactObject'));
console.log(retreivedContactObject);

For easier handling, ensure that your registerForm FormControl names match those of your student object.

import { FormBuilder, FormGroup, Validators } from '@angular/forms';
  .
  .

student = {
  contact: {
    custName: undefined,
    custAddress: undefined,
    custTown: undefined,
    .
    .
  }
};

constructor(private formBuilder: FormBuilder) { }

registerForm: FormGroup = this.formBuilder.group({
  custName: [null, Validators.required],
  custAddress: [null, Validators.required],
  custTown: [null, Validators.required],
    .
    .
},

Once your formControls align with your student object's properties,

you can update your student using:

this.student.contact = {...this.registerForm.value};
//console.log(this.student);

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

jQuery Load - Oops! There seems to be a syntax error: Unexpected token <

Error: Uncaught SyntaxError: Unexpected token < I encountered the error message mentioned above while trying to execute a jQuery load function: $('#footer').load(UrlOfFooterContent); The variable UrlOfFooterContent holds the URL of an MVC c ...

What is the syntax for creating a link tag with interpolation in Angular 2 / Ionic 2?

As I work on developing an app using Ionic 2/Angular 2, I have encountered a challenge that I am struggling to overcome. Let me provide some context: I am retrieving multiple strings from a webservice, and some of these strings contain links. Here is an e ...

How can I combine my two ngIf conditions into an ngIf else statement?

Having trouble incorporating an *ngIf else with two large <div> elements, as the content seems overwhelming to organize properly while following the documentation. Initially believed that using the same styling for two open text boxes, with one hidd ...

Utilize the Google Drive API to easily upload an Excel file

I'm encountering an issue with the Google Drive API. I've been attempting to upload an Excel file using this API, but haven't had any success. I even tried following the instructions in the Google API documentation without luck. Below is a ...

Do I have to include reject() in the executor when using promises in express.js?

If we choose not to handle rejection, is it necessary to include the reject parameter in the promise executor? For example: new Promise((res) => { res(a); }) ...

Ensuring TypeScript recognizes a class property as definitively initialized when set using a Promise constructor

I have a simple class definition that is giving me an error in TypeScript. class Container { resolveData: (s: string) => void // not definitely initialized error! data: Promise<string> constructor() { this.data = new Promise&l ...

Creating an Account with Firebase

I've created a function called signup in my web project that uses JavaScript to add a user to my Firebase database. The function works fine, but I'm encountering an issue when I try to redirect to another page at the end of the function - the use ...

JQuery function fails to execute upon first page load

I am currently facing a situation where I need to wait for a specific image to load before either swapping out its src or showing/hiding the next image. The desired outcome is to display a placeholder image (silhouette) until the main image loads, then hi ...

Issue with Mongoose Promise failing to transfer data to the following chain

When querying MongoDB using mongoose with promises, I encounter an issue where the result is only accessible in the initial .then(function(results){ // can send the result from here..}). However, when I manipulate the results and attempt to pass them to th ...

The Access-Control-Allow-Origin policy does not permit requests from applications running with an origin of null, specifically for those using a file:// URL

I am in the process of creating a webpage that utilizes jQuery's AJAX feature to fetch images from both Flickr and Panoramio. While the image retrieval from Flickr is functioning properly, I encounter an issue when attempting to use $.get(url, callba ...

A solution for managing MUI data grid rows and columns using useRef to prevent infinite loops when handling onSortModelChange

I am encountering a similar issue as described in the question below. A suggestion was given to utilize useRef to encapsulate rows and columns and access its .current value. How can I implement this solution?? Material-UI Data Grid onSortModelChange Causi ...

How to implement a feature for uploading multiple files through a single form with unique input fields in a web

After searching on Stack Overflow, I couldn't find a suitable solution for my problem. I need help with my code that fetches data and sends it to a PHP file to upload files to specific folders and store their links in a database. However, I am encount ...

Unable to retrieve JSON data in Angular2 as expected

I am encountering an issue while attempting to retrieve data from a JSON file stored in my assets folder within Angular 2. The data is not displaying as expected despite my efforts. The JSON file I am trying to access is named: test.json [ "{'id ...

Accessing a property's value from a different property within a Class' initialization function

I encountered a challenge while trying to access the value returned in one method within a property of another method belonging to a different constructor. The specific error message I received was "TypeError: Cannot read property 'name' of undef ...

Removing a specific item from a Kendo UI dropdown list

Recently, I encountered a predicament with a dropdownlist populated from a datasource. Following a certain event, my goal is to eliminate a single item from the dropdownlist identified by id = 22. Although I recognize this may not be the best practice du ...

What could be the reason for the unexpected outcome when checking if display is equal to "none"?

I have a JavaScript function called "display()". I want to hide my navigation menu on click, but it is not working properly - it just blinks. I am looking for a solution that uses only JavaScript and does not involve querySelector. function display() { ...

Acquire Formik Validation for the Current Year and Beyond

How can I ensure that the input in Formik is restricted to the currentYear and later years only? const currentYear = new Date().getFullYear(); expiryYear: yup .string() .required('Please select an expiry year') .min(4, `Year format must be grea ...

Implementing dynamic component swapping in Vue 3 using components from another component

I currently have a display component called app-display, which contains a dynamic component inside (by default, it is set to app-empty): app.component('appDisplay', { template: `<component :is="currentComponent"></c ...

What is the reason behind not being able to utilize addEventListener on a variable that has been selected through DOM's getElementsByClassName method?

btn = document.getElementsByClassName('btn'); value = document.getElementById('value'); let counter = 0; btn[2].addEventListener('click', function() { if (btn[2].classList.contains('decrease')) counter -= 1; if ...

`Switching the selection in ng-selected`

I am having trouble toggling ng-selected options in Angular. I have tried the following approach: <select ng-model="datacut.ages" multiple> <option value="" disabled="disabled">Please Select</option> <option value="0-15" ng-clic ...