[英]How to map correctly two arrays with booleans
我有一個列表accounts
。 我也有一個列表accountsWithSelectedField
我映射如下:
this.accountsWithSelectedField = this.accounts.map(s => ({...s, selected: false}));
現在,從 http 請求中,我收到了accountsSetups
列表(已選擇的帳戶)。 我應該相應地 map 一切。 基本上它應該是這樣的:
accounts: 111, 222, 333, 444
accountsWithSelectedField: {111: false}, {222: false}, {333: false}, {444: false}
accountSetups(from http): {222, true, true}, {333, true, false}
After mapping => accountsWithSelectedField: {111: false}, {222: true}, {333: true}, {444: false}
我需要幫助弄清楚如何正確地 map 它,我嘗試這樣做,但有一些問題,要么 iban 沒有顯示,要么一切都被映射為真實。
this.accountsWithSelectedField = this.accounts.map(o => data.accountSetups.map(s => ({
iban: o.iban,
selected: s.someBoolean || s.anotherBoolean
})));
也試過這樣:
for (const account of this.accountsWithSelectedField) {
for (const acc of data.accountSetups) {
if (account.iban === acc.account.iban) {
console.log(account.iban + ' is true');
account.selected = true;
}
}
}
我得到了 6 個 ibans 中的 3 個is true
(正確),但是所有 6 個都被選中了,我不明白為什么?
我會做這樣的事情:
const accounts = [111, 222, 333, 444];
const accountsWithSelectedField
= accounts.map(account => ({id: account, someBoolean: false}));
const accountSetups = [
{id: 222, someBoolean: true, anotherBoolean: true, iban: '123'},
{id: 333, someBoolean: true, anotherBoolean: false, iban: '456'}
];
for (const accountSetup of accountSetups) {
const associatedAccount = accountsWithSelectedField.find(account => account.id === accountSetup.id);
if (associatedAccount) {
associatedAccount.someBoolean = accountSetup.someBoolean || accountSetup.anotherBoolean;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.