Creating an array by extracting form values in Angular

In my component, I have the following function:

updateInfo(info: NgForm) {
    const changedValues = Object.keys(info.controls)
      .filter(key => info.controls[key].dirty === true)
      .map(key => {
        return { control: key, value: info.controls[key].value }
      });
    console.log(changedValues);
}

This function logs the changes in form values, but now I want to create an array using changedValues like this:

{ firstName: "john", lastName: "sam" }

How can I achieve that?

Edit: Currently, the console log output looks like this

[
{firstName: "john"},
{lastName: "sam"}
]

Answer №1

Avoid using the map method as it returns an array. Instead, utilize the forEach method and populate your object with the items:

updateInfo(info: NgForm) {
  const modifiedValues = {};
  Object.keys(info.controls).forEach(key => {
    if (info.controls[key].dirty) { 
      modifiedValues[key] = info.controls[key].value;
    }
  });
  console.log(modifiedValues);
}

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

Unable to retrieve any response data in Angular 2

I'm having trouble retrieving the response from my API. Despite being able to do so with PostMan, my variable "this.data" remains null. I've experimented with various approaches to no avail. Any assistance would be greatly appreciated. The method ...

What could be causing the Angular Material Dialog component to not display properly in Google Chrome?

I encountered an issue with the dialog box when testing it in different browsers. It seemed to work fine in Firefox, but in Chrome, the click event only displayed a small empty dialog box without any content or buttons. This problem arose while I was follo ...

RxJS: Transforming an Observable array prior to subscribing

I am retrieving data (students through getStudents()) from an API that returns an Observable. Within this result, I need to obtain data from two different tables and merge the information. Below are my simplified interfaces: export interface student Stude ...

Extracting values from an *ngFor loop in Angular 8 - Here's how to do

Currently, I am utilizing *ngFor to display some data. I have a requirement to extract a specific value from *ngFor and display it in, for instance, my heading. However, when I attempted to use {{ project }}, it consistently returned undefined. Despite hav ...

I'm curious about how to efficiently add a new item to an array using react-dnd. Does anyone have any suggestions or insights on this

I am currently working on a project where I want to implement drag and drop functionality using react-dnd. However, after making some changes, the drag and drop feature doesn't seem to work properly for newly added items in the array. Is there a way ...

What causes the component's constructor to be invoked multiple times instead of being efficiently reused by the router?

I came across this interesting article where the writer discusses how the router reuses components to avoid unnecessary DOM modifications: In order to prevent unnecessary changes to the DOM, the router will reuse components when the parameters of the co ...

Angular 5 APP_INITIALIZER: Provider parse error - Cyclic dependency instantiation not possible

I am utilizing the APP_INITIALIZER token to execute a task upon page load before my Angular application is initialized. The service responsible for this functionality relies on another service located within my CoreModule. The issue at hand seems to be ab ...

Pootle is generating PHP array files with inaccurate content

Lately, I've been utilizing Pootle to translate a small PHP project. Our internationalization files are formatted as arrays in PHP, like this: return array( 'word.in' => 'en', 'word.yes' => 'Sí', ...

Looping through an array of JSON objects without keys in Java for an Android application

I am looking to loop through a JSON array containing objects, but all the tutorials I've found are for keyed JSON objects. This is how the JSON array appears: items:[{i know}, {what you did} ,{last summer}] ...

Issues arise when attempting to extract data from a data provider using JSON within the context of the Ionic framework

Hey there! I'm relatively new to the world of Angular and Ionic, and I've embarked on a project to create a pokedex app. My approach involves using a JSON file containing an array of "pocket monsters". However, my current challenge lies in extrac ...

The property 'label' is not found in the 'string' type in Typescript

Below is the code snippet I am using: interface State { resourceGroup: QuickPickItem | string; } setEvent(state.resourceGroup?.label).catch(err => console.error(err)); When executing this code, I encountered the following error messa ...

Angular offers a simple solution for adding events to all "p", "span", and "h1" elements easily

I am attempting to implement a "double click" event on all text HTML elements (p, span, h1, h2, etc.) across all pages in order to open a popup. I believe there should be a more efficient way than adding (dblclick)="function()" to each individual element. ...

In JavaScript, creating a new array of objects by comparing two arrays of nested objects and selecting only the ones with different values

I've been struggling to make this work correctly. I have two arrays containing nested objects, arr1 and arr2. let arr1 =[{ id: 1, rideS: [ { id: 12, station: { id: 23, street: "A ...

Tips for parsing text responses in React to generate hyperlinks and emphasize specific words

I'm currently tackling a React project and facing an interesting challenge. I have a text response that needs to be parsed in a way that all URLs are automatically turned into clickable hyperlinks (using anchor tags). Moreover, there's a requirem ...

Strategies for redirecting search queries when adding a new path

Issue I am facing a challenge with pushing a new path to the URI while maintaining existing search queries. For example: Current URL: https://example.com/foo?bar=123&foobar=123 When I use history.push('newPath'), I end up with https://exa ...

Troubleshooting: Angular2 fails to send HTTP GET requests

There seems to be an issue with the code provided in (A) where it fails to send its HTTP request when `test()` is called. In contrast, the similar code in (B) functions properly. Do you have any insights into what might be causing this problem? I can confi ...

The mat-datepicker is being displayed beneath the content

My Angular material design datepicker is displaying underneath the content. Within my module, I have a component that is rendered inside app-root. This component includes a mat-stepper with a mat-datepicker inside one of the steps. This is how the genera ...

Typescript error handling: Handle 404s on all Koa routes

Issue Encountering problems while setting up Auth Controllers Difficulty using Bcrypt and JWT for encryption All POST Calls to Koa resulting in 404 errors Calls to other routes are functioning correctly Potential issue with the scope of the code. impo ...

The Angular downgradeComponent feature is experiencing difficulties in its creation process

I recently set up a hybrid application using AngularJS and Angular 5 with downgradeModule. I successfully converted a small component from AngularJS to Angular, but unfortunately, it is not being created. I've added console.logs in different parts of ...

Encountering issues during the installation of node modules

An error log is displayed below: 1027 error gyp verb check python checking for Python executable "python2" in the PATH 1027 error gyp verb `which` failed Error: not found: python2 1027 error gyp verb `which` failed at getNotFoundError ...