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

Issue with Swiper js "autoheight" not resizing correctly for the height of the first slide upon page initialization

Hey everyone, I'm encountering a problem with my reactapp and I'm not sure how to resolve it. I've spent a considerable amount of time searching on stackoverflow but haven't come across any helpful solutions. The issue is related to a ...

CSS: Problem Arising from Line Connections Between Tree Elements

I'm currently working on connecting tree nodes with lines in a drawing. I've managed to achieve it to some extent, but there are a few issues like dangling lines that I need to fix. You can find the implementation on codepen here: https://codepe ...

Produce configuration files on the fly for Angular Component Testing using @Component declarations

Looking to test an Angular 11 component: @Component({ selector: 'app-foo-page', template: ` <app-header mode='operational' cool='true'></app-header> Some content ` }) export class FooPageComponent { } ...

Unable to remove the necessary row with Angular.js/JavaScript

I am facing an issue in deleting the correct row from an array using Angular.js. Below is the code snippet that I am working with: <tr ng-repeat="d in days"> <td>{{d.day_name}}</td> <td> <table ...

RouterLink causing component not to reload

In my welcome.component, I have a menu and tab. When I click on a menu item, the routerlink doesn't initiate a new request, causing the tab component not to reload. The tab component is called by multiple router links and should be reloaded every time ...

Using JavaScript to place a particular tag at a designated position

I have a string that looks like this: var txtstr='<p>Text 1</p><p>&nbsp;</p><p>Text &nbsp;2</p><p>&nbsp;</p><p>Text 3&nbsp;</p>'; I have an <img src=..../> tag and ...

Issue with Angular 8 Material: mat-option remains unselected after update

When using Angular 8, I encountered an issue where the mat-option was not selecting a specific option. It worked fine when I used static options, but failed on dynamic mat-options. <mat-label>Item Category {{item.category_id}}</mat-label> & ...

Chrome experiences a crash during regular expression matching operations

I have a challenge where I am attempting to validate 50 email addresses separated by commas using regex. Strangely, every time I run this operation, Chrome crashes. However, Safari seems to handle it without any issues. Below is the code snippet that I am ...

What is the best way to incorporate a routerLink in an HTML string?

For my app, I need to display a long piece of text using HTML strings. Here is an example: // component description: string = `<p>Hello world. <a routerLink="/home">Click here</a> to go to the home page.</p>`; // template <div ...

Guide on setting a v-model within a v-for loop (using an example from Bootstrap Vue)

Currently, I am utilizing vue-bootstrap for creating input fields using a v-for directive. The objective is quite similar to the example provided in this link. However, I am encountering some difficulties in obtaining the data collected from these inputs i ...

Is there a way to dynamically switch between AngularJS modules based on a configuration change?

Understanding the inner workings of Dependency Injection with AngularJS modules has sparked an idea in my mind. I thought about leveraging this concept to switch between different modules based on the environment of the application. For instance, I aim to ...

Tips for managing the output of an asynchronous function in TypeScript

The casesService function deals with handling an HTTP request and response to return a single object. However, due to its asynchronous nature, it currently returns an empty object (this.caseBook). My goal is for it to only return the object once it has b ...

What is the best way to include an external JavaScript file in a Bootstrap project?

I am brand new to front-end development and I'm attempting to create an onClick() function for an element. However, it seems like the js file where the function is located is not being imported properly. I've tried following some instructions to ...

Ways to display spinner animations during image loading on Next.js?

Currently, I am attempting to implement a spinner display while images are loading on a Next.js website. To achieve this, I am utilizing the NextUI UI library. My website features several cards, and my goal is to showcase a spinner during the image loadin ...

Adding new data to a Chart.js line graph in vue on form submission - A step-by-step guide

I'm struggling with dynamically updating my line chart with new data. I want the chart to refresh every time a user submits a form with new data. Currently, I can add new data to the datasets array in the data function of App.vue, but the chart doesn& ...

Double invocation of useEffect causing issues in a TypeScript app built with Next.js

My useEffect function is set up with brackets as shown below: useEffect(() => { console.log('hello') getTransactions() }, []) Surprisingly, when I run my app, it logs "hello" twice in the console. Any thoughts on why this might be ...

What is the best way to assign Reference Identification numbers to the orders?

Is there a way for me to obtain and attach the id reference to the order? I have retrieved the product and user ids. When I utilize my get method, it should retrieve all the details about the products and users. For instance, the data will display compreh ...

When using Firefox to run an Angular dev server with the --ssl flag, an error with the code SEC_ERROR_INADEQUATE_KEY

Currently, I have my angular application running using the command ng serve --port 5001 --ssl --no-live-reload Everything was working fine for a few months until recently when Firefox started having issues loading the page. The error message displayed is: ...

Obtain every possible sequence of US phone number segments for a provided number

The format of a US phone number is as follows: (XXX) XXX-XXXX Given a string consisting only of digits with a length between 0 and 10, I want to generate an array of all possible chunks that match the US phone number format. For example: Input: "54" Out ...

What is the process of enabling scrolling on the main panel once scrolling on the sidebar has concluded?

How can I achieve a scrolling behavior similar to the one demonstrated here? When scrolling through the sidebar, I want it to continue scrolling until it reaches the end. After that, any further scrolling on the sidebar should scroll the main panel inste ...