Use a function on values that have corresponding keys in a separate array

I am working with a form.value object that looks like this:

 form.value = {
  "to_date": "2019-03-21T05:00:00.000Z",
  "from_date": "2019-03-13T05:00:00.000Z",
  "is_form": ""
  "errors":""
}

Additionally, I have an array called filterArray:

filterArray = [
  "from_date",
  "to_date"
]

The goal is to loop through the keys in the form.value object and apply a function (converFormat()) to the values of keys that match the ones in the filterArray:

form.value = {
  "to_date": "2019-03-21T05:00:00.000Z",       // function() applied since key in filterArray  
  "from_date": "2019-03-13T05:00:00.000Z",     // function() applied since key in filterArray  
  "is_form": ""                               
  "errors":""                                  
}

Answer №1

Transforming selected keys in a form object using a custom function:

Object.keys(formData).filter(key => filterKeys.includes(key)).forEach(key => {
  formData[key] = transformData(formData[key])
})

// Alternatively, you can store the transformed values in another variable

const customizedFormData = {
  ...formData,
  ...Object.keys(formData)
    .filter(key => filterKeys.includes(key))
    .reduce(
      (previousVal, currentKey) => ({
        ...previousVal,
        [currentKey]: transformData(formData[currentKey])
      }),
      {}
    )
};

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

When using Angular with mdbootstrap, the mdb-tabs directive will move to the end if the ngIf condition is true

Currently facing a challenge with a significant amount of code here. It is referenced as follows: "ng-uikit-pro-standard": "file:ng-uikit-pro-standard-8.3.0.tgz", I am attempting to display a tab between 1 and 3 if a certain condition ...

When converting a PDF to a PNG, the precious data often disappears in the process

I am currently facing a problem with the conversion of PDF to PNG images for my application. I am utilizing the pdfjs-dist library and NodeCanvasFactory functionality, but encountering data loss post-conversion. class NodeCanvasFactory { create(w, h) { ...

Share information by including the provider within the @component declaration in Angular

I am looking to explore a new method of passing data using providers directly within the component itself. For instance, I am curious if there is a way to pass a variable from one component to another without relying on routing or other traditional methods ...

What is the best way to include the existing query string value in the hyperlinks on my page?

My main coding objective is to simultaneously search multiple websites. To accomplish this, I want to create a query string containing the search terms (primarily for analytics purposes) using a form. By utilizing JavaScript, I am aiming to include the s ...

Having trouble with clearInterval in React TypeScript?

I have been encountering issues with the clearInterval function in TypeScript for React. I am not sure why the interval is not being cleared. To address this problem, I defined a variable let interval_counter;, and used it as follows: interval_counter = ...

Tips for resolving the issue of "The types 'GameState' and 'string' do not intersect, so this condition will always yield 'false'."

I need to display different components based on the value of gameStatus: import React from "react"; import { useAppSelector } from "./hooks/redux"; import EndScreen from "./pages/EndScreen"; import QuestionsPage from "./p ...

Iterate through nested objects in Javascript

I am having trouble extracting only the word from each new instance of the newEntry object. It shows up in the console every time I add a new word, but not when I assign it to .innerHTML. Can someone assist me with this issue? Full code: <style ty ...

TypeScript: Despite declaring specific types, generic functions still treat parameters as "any"

When using TypeScript 4.4.3, I am looking to specify the types of function parameters for a function that returns a generic. However, TypeScript seems to be treating the parameters as any when working with functions that involve generics. Here's a si ...

TypeScript encountered an error with code TS2554, indicating that it was expecting 0 arguments but instead received 1 in an Ionic application

Hello everyone! I'm encountering an issue in my project involving a Type Script error TS2554: Expected 0 arguments, but got 1. This error is preventing me from being able to select other options for custom input pop up. In this forum post, I have shar ...

Modify the style of an element using a media query and Angular 4

Is there a way to update a class of an element based on the browser's width in my .ts file? matchMedia('(max-width: 400px)').addListener((mql => { if (mql.matches) { this.myclass = 'toggled'; } })); In the HTML, it shou ...

Angular5: At what point does Angular finish loading a page?

Within my angular5 application, I have implemented a table that retrieves data from the backend. After the initial load of the table, I aim to adjust the scroll position inside it. To achieve this, I am utilizing the following code: ngAfterViewInit() { ...

The bespoke node package does not have an available export titled

No matter what I do, nothing seems to be effective. I have successfully developed and launched the following module: Index.ts : import ContentIOService from "./IOServices/ContentIOService"; export = { ContentIOService: ContentIOService, } ...

Activating the loader dismiss command will transition the swiper to the current page

Having a swiper and loader makes the scenario very straightforward. The loader is initialized whenever calculations are performed, and after successfully obtaining the result, the loader turns off and swipes to the second slide. <swiper-container #sl ...

The Angular2 application was constructed using angular-cli, incorporating a directive, and optimized with the ng build

I am working on an angular-cli app and my environment details are: npm -v 3.10.8 node -v v6.9.1 angular2 ^2.4.0 angular/cli 1.0.0-beta.32.3 Recently, I added the following line to my package.json: "angular2-auto-scroll": "1.0.12" You can find more info ...

Unable to retrieve data from Angular service to component

My service function involves querying the database for products. getPro():any{ this.database.all("SELECT * FROM product").then(rows => { console.log("hello pro hear....") let productList:Product[]=[] for(var row in rows) { ...

Utilizing Arrays in MySQL and Perl: Tips for Integrating an Array with the IN Clause in a Select Statement (WHERE IN (@array))

Recently, I was able to solve a question that involved finding zip codes within x miles in Perl. I have the necessary array @zips at my disposal now. However, when attempting to incorporate this array into a query like the one below, I seem to face numero ...

Mocking is not working for request scoped injection

I'm encountering an issue with mocking the return value of a provider, as it seems to be clearing out the mock unexpectedly. Module1.ts @Module({ providers: [Service1], exports: [Service1], }) export class Module1 {} Service1.ts @Injectable({ ...

Are there any methods within Angular 2 to perform Angular binding within a string?

When creating an HTML template with routing, such as shown below: <ul class="sb-sub-menu"> <li> <a [routerLink]="['clientadd']">Client Add</a> </li> </ul> It functions as expected. However, w ...

Using the increment operator within a for loop in JavaScript

this code snippet causes an endless loop for (let i = 0; ++i;) { console.log(i) } the one that follows doesn't even run, why is that? for (let i = 0; i++;) { console.log(i) } I want a thorough understanding of this concept ...

When testing my POST request online, it functions properly. However, I am facing difficulties in getting it to work in next.js as I keep receiving a 405

I am currently working on establishing a connection to Zoho Creator in order to retrieve some data. After successfully testing the request on and receiving the correct response, I encountered an issue while trying to implement it within a next.js applicat ...