簡體   English   中英

在數組中查找具有相同值屬性的對象

[英]Find objects in array with same value property

我有一系列銀行賬戶,它們是從 GET 請求中收到的。

<div class="card" *ngFor="let acc of accounts">{{acc.iban}}  ({{acc.currency}})>

例如,帳戶數組是這樣的:

this.accounts = [
    { iban : '123' , currency: 'EUR' },
    { iban:  '123' , currency: 'USD' },
    { iban:  '234' , currency: 'EUR' }
]

如何動態查找具有相同 iban 的帳戶,從列表中刪除其中一個帳戶,並將刪除的帳戶的貨幣添加到另一個帳戶?

預期的輸出是:

this.accounts = [
    { iban: '123' , currency 'EUR, USD' },
    { iban:  '234' , currency: 'EUR' }
]

您可以使用Object.values()Array.prototype.reduce()將具有相同 IBAN 的帳戶合並,並用逗號連接貨幣。

使用reduce ,您迭代您的accounts數組並構建一個將iban映射到合並帳戶的中間字典,然后使用Object.values()枚舉字典條目的值以返回一個數組。

 const accounts = [ { iban : '123' , currency: 'EUR' }, { iban: '123' , currency: 'USD' }, { iban: '234' , currency: 'EUR' } ]; const result = Object.values(accounts.reduce((acc, { iban, currency }) => { acc[iban] = acc[iban] ? { ...acc[iban], currency: acc[iban].currency + ', ' + currency } : { iban, currency }; return acc; }, {})); console.log(result);

暫無
暫無

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

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