0

I have a child component, in which, after button press it pass a form field to a father component. I have to pass this fields as query Params to an API GET /valuation/ that require more or less 20 optional parameters, in which the name differs from Input fields.

I created a temporary object res inside the father function accept in which I iterate the field . Still I can't figure how to pass this parameter inside the object res, using multiple if is dirty code.

for example Function in father component

    accept(form:any){
        const req: any = {};
        if(form.name)
          req.user = form.name
        if(form.address)
          req.clusterAddress = form.address
       ... and so on x 20 times

this.requestService.getRequest(req).subscribe(
      (response) => {
        this.getRequest(response);
      }, (error) => {
        console.error(error);
      }
      }

As you can see this is not a viable option, what I can use to take dynamically the query param names?

3
  • Your question contains lots of unnecessary information. What you want to do, is to remove falsy values from a JavaScript object. The question isn't related to query params, HTTP requests, Angular, AngularJS and TypeScript. Please simplify your question. Commented May 20, 2022 at 10:35
  • Forgive me but I don't understand your answer, nor what are the unnecessary informations. I have to pass it to a service in which it gets those possible 20 parameters. Ok to remove falsy values from form, but how can I assign the fields, if the names doesn't match the ones in form? I have to assign singularly one by one? That's basically my question. Commented May 20, 2022 at 10:55
  • You can use a map... make another object that holds the information about which property from the form object maps to which property on the res object. Iterate through the keys of this object, make your falsy check and assign :). Commented May 20, 2022 at 11:02

1 Answer 1

1

You can use a map to store information about which property from the form maps to which property on your res object and then iterate through the keys, check for the presence of the value and assign:

const formToResMap: { [key: string]: string } = {
  name: 'name',
  address: 'clusterAddress',
  // ...
};

accept(form: any) {
  const req = Object.keys(formToResMap).reduce((acc, key) => {
    if (form[key]) {
      acc[formToResMap[key]] = form[key];
    }
    return acc;
  }, {});
  console.log(req);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I think that's the correct way!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.