簡體   English   中英

如何使用 ES6 Object spread 更新數組內的對象?

[英]How to use ES6 Object spread to update object inside array?

我有以下來自響應的對象數組:

const baseInput = [{
    PaymentRequirementsDetail:
    { dateDue: '12/02/2019',
        outstandingMinimum: { Money: { amount: '5.20', code: 'GBP' } },
        overlimit: { Money: { amount: '345.20', code: 'GBP' } },
        arrears: { Money: { amount: '345.20', code: 'GBP' } } }
},
{ Account: {},
    AccountId: '00000012345',
    CardBrand: 'SOMEBRAND',
    isAccountElibible: false,
    Customer:
    { salutation: 'Mr',
        givenName: 'James',
        familyName: 'Jamesy',
        suffix: 'Dr' },
    Delinquency: { monthsInArrears: 0, isOverlimit: true } }]

然后我用一堆函數轉換響應,並返回一個友好的、格式化的上述版本。

const baseOutput = transform(baseInput);

這將返回:

   {    name: 'Mr James Jamesy, Dr',
        cardBrand: 'SOMEBRAND',
        isAccountElibible: false,
        delinquency: { monthsInArrears: 0, isOverlimit: true },
        dateDue: '12/02/2019',
        outstandingMinimumAmount: 'GBP, 5.20',
        overlimitAmount: 'GBP, 345.20',
        arrearsAmount: 'GBP, 345.20' }

我現在想對此進行測試並生成一些快照。

我可以將上面的代碼復制/粘貼到我的測試用例中,並在我做我的斷言時更改值,效果很好。 像這樣;

    test('should omit suffix if it is undefined', () => {
    const input = [{
        PaymentRequirementsDetail:
        { dateDue: '12/02/2019',
            outstandingMinimum: { Money: { amount: '5.20', code: 'GBP' } },
            overlimit: { Money: { amount: '345.20', code: 'GBP' } },
            arrears: { Money: { amount: '345.20', code: 'GBP' } } }
    },
    { Account: {},
        AccountId: '00000012345',
        CardBrand: 'SOMEBRAND',
        isAccountElibible: true,
        Customer:
        { salutation: 'Mr',
            givenName: 'James',
            familyName: 'Jamesy' },
        Delinquency: { monthsInArrears: 0, isOverlimit: true } }];

    const output = transform(input);

    expect(baseOutput).toMatchDiffSnapshot(output);
});

這將根據我的需要生成我的快照,我將能夠清楚地看到帶有后綴的版本和沒有后綴的版本之間的區別。

但是我相信有一種更簡潔的方法可以使用對象擴展運算符來做到這一點。 而不是上面的所有代碼,我應該留下;

 const input = [{
        ...baseInput,
        Customer:
        { salutation: 'Mr',
        givenName: 'James',
        familyName: 'Jamesy'
        }
    }];

但是,我無法以某種方式利用擴展運算符來實現這一目標。 誰能看到我的錯誤在哪里?

您的baseInput是一個包含兩個項目的數組。 擴展運算符適用於數組或對象,您在這里所做的是將數組擴展到目標對象中。

如果您的模型沒有改變,您可以簡單地將索引對象傳播到您的目標中,如下所示:

const input = [{
    ...baseInput[0]
  },{
        ...baseInput[1],
        Customer:
        { salutation: 'Mr',
        givenName: 'James',
        familyName: 'Jamesy'
        }
    }];

https://stackblitz.com/edit/typescript-imcqkh?file=index.ts

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM