简体   繁体   中英

How to assign values to object that has similar keys?

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
 }
}

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.

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'})); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM