简体   繁体   English

在数组中查找具有相同值属性的对象

[英]Find objects in array with same value property

I have an array of bank accounts, which I receive from a GET request.我有一系列银行账户,它们是从 GET 请求中收到的。

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

Accounts array is for example like that:例如,帐户数组是这样的:

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

How can I dynamically find accounts with the same iban, remove one of them from the list, and add removed the account's currency to the other account ?如何动态查找具有相同 iban 的帐户,从列表中删除其中一个帐户,并将删除的帐户的货币添加到另一个帐户?

The expected output is:预期的输出是:

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

You can use Object.values() and Array.prototype.reduce() to merge the accounts with the same IBAN and join the currencies with a comma.您可以使用Object.values()Array.prototype.reduce()将具有相同 IBAN 的帐户合并,并用逗号连接货币。

With reduce , you iterate on your accounts array and build an intermediate dictionary that maps the iban to the merged accounts, then with Object.values() you enumerate the values of the dictionary entries to return an array.使用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