0

just wanted to avoid if statements is there way to assign values to object if they have similar keys in response instead of checking each object with if ?

what could be efficient approach here ?

main.ts

  public responsehandler(@Body()data: any): any {
        const response: Idetails = {} as Idetails;
        if (data.details === undefined || data.details === null) {
           return data;
        }
        if (data.details) {
            if (data.details.primary) {
                response.details.primary.beginningBalance = data.details.primary.beginningBalance;
                response.details.primary.endingBalance = data.details.primary.endingBalance;
            }

            if (data.details.secondary) {
                response.details.secondary.beginningBalance = data.details.secondary.beginningBalance;
                response.details.secondary.endingBalance = data.details.secondary.endingBalance;

            }

        }
        return response;
    }

interface.ts

export interface Idetails {
 primary:balanceDetails;
 secondary: balanceDetails;
}

export interface balanceDetails {
     beginningBalance: string;
     endingBalance: string;
}

data

details: {
 primary: {
   beginningBalance: 458,
   endingBalance: 890
 }, 

 secondary: {
   beginningBalance: 47,
   endingBalance: 871
 }
}
Scott Rudiger
  • 1,224
  • 12
  • 16
hussain
  • 6,587
  • 18
  • 79
  • 152
  • 2
    Possible duplicate of [How to copy matching properties from one object to another](https://stackoverflow.com/questions/36441682/how-to-copy-matching-properties-from-one-object-to-another) – Simon Groenewolt Oct 22 '18 at 17:27

2 Answers2

0

Check this out: https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Objetos_globales/Object/hasOwnProperty

You could try this approach:

public responsehandler(@Body()data: any): any {
    const response: Idetails = {} as Idetails;
    if (!data.details) {
         return data;
    }

    for (const key in response.details) {
            if (data.details.hasOwnProperty(key)) {
                    response.details[key] = data.details[key];
            }
    }

    return response;
}

You should check more validations or conditions to make it work for you.

Koken
  • 102
  • 6
0

If your goal is just to avoid if statements, you could rewrite it like so:

// in js (sorry not a ts user)

function responseHandler(data) {
  return data.details == null ? data : {details: {...data.details}};
}

console.log(responseHandler({details: {primary: {beginningBalance: 0, endingBalance: 1}}}));

console.log(responseHandler({details: {secondary: {beginningBalance: 0, endingBalance: 1}}}));

console.log(responseHandler({noDetails: 'oopsy'}));
Scott Rudiger
  • 1,224
  • 12
  • 16