如何为具有相似键的对象分配值?

时间:2018-10-22 16:25:49

标签: javascript angular typescript

只是想避免if语句在响应中具有相似键的情况下可以将值分配给对象,而不是用if检查每个对象?

什么是有效的方法?

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

数据

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

 secondary: {
   beginningBalance: 47,
   endingBalance: 871
 }
}

2 个答案:

答案 0 :(得分:0)

查看以下内容:https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Objetos_globales/Object/hasOwnProperty

您可以尝试这种方法:

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

您应该检查更多验证或条件,以使其适合您。

答案 1 :(得分:0)

如果您的目标只是避免if语句,则可以这样重写它:

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