I am using mat-stepper single form for my stepper. when i do API call it sends data as an array of objects like this:
[ { "product": "lifeci", "gender": "F", "birthDate": "1999-04-23T10:58:53.839Z", "payFrequency": 12, "subLimit": "100" }, { "currency": "USD", "amount": "15000", "period": 3 } ]
I would like to send data as one object like this:
{ "gender": "string", "birthDate": "2021-04-23T11:37:01.738Z", "period": 0, "payFrequency": 0, "amount": 0, "subLimit": "string", "currency": "string", "product": 0 }
this is my form:
this.formGroup = this._formBuilder.group({ formArray: this._formBuilder.array([ this._formBuilder.group({ product: ['lifeci', Validators.required], gender: ['', Validators.required], birthDate: ['', [Validators.min(18), Validators.max(50)]], payFrequency: [12], subLimit: ['100'] }), this._formBuilder.group({ currency: ['USD', Validators.required], amount: ['15000', Validators.required], period: ['', Validators.required], }), ]) }); onSubmit() { this.service.calculate(this.formGroup.value).subscribe( (res:any)=>{ console.log(res); }, err => { console.log(err); } ); }
service.ts
export class LifeciService { readonly API_SERVER = "API_URL"; constructor(private http: HttpClient) { } calculate(formData) { return this.http.post(this.API_SERVER + '/Calculate', formData); } }
how can i do it?
Advertisement
Answer
You can use a simple transformation using javascript reduce
function to transform the data to the desired structure
const initial = [ { "product": "lifeci", "gender": "F", "birthDate": "1999-04-23T10:58:53.839Z", "payFrequency": 12, "subLimit": "100" }, { "currency": "USD", "amount": "15000", "period": 3 } ]; const reduced = initial.reduce((prev, next) => ({...prev, ...next}), {}) console.log(reduced)
In your case this can be implemented like below
onSubmit() { const formArrayData = this.formGroup.get('formArray').value; const data = formArrayData.reduce((prev, next) => ({...prev, ...next}), {}) this.service.calculate(data).subscribe( (res:any)=>{ console.log(res); }, err => { console.log(err); } );