简体   繁体   English

如何正确使用布尔值 map 两个 arrays

[英]How to map correctly two arrays with booleans

I have a list accounts .我有一个列表accounts I also have a list accountsWithSelectedField which I mapped like this:我也有一个列表accountsWithSelectedField我映射如下:

this.accountsWithSelectedField = this.accounts.map(s => ({...s, selected: false}));

Now from an http request I receive a list of accountsSetups (accounts that were selected).现在,从 http 请求中,我收到了accountsSetups列表(已选择的帐户)。 I should map everything accordingly.我应该相应地 map 一切。 Basically it should look like this:基本上它应该是这样的:

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}

I need help figuring out how to map it correctly, I tried doing it like this, but there are some issues, either the iban is not showing, or everything is mapped as a true.我需要帮助弄清楚如何正确地 map 它,我尝试这样做,但有一些问题,要么 iban 没有显示,要么一切都被映射为真实。

this.accountsWithSelectedField = this.accounts.map(o => data.accountSetups.map(s => ({
       iban: o.iban,
       selected: s.someBoolean || s.anotherBoolean
     })));

Also tried like this:也试过这样:

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

And I got 3 out of six ibans is true (correct), but all six of them were selected, I can't understand why?我得到了 6 个 ibans 中的 3 个is true (正确),但是所有 6 个都被选中了,我不明白为什么?

I would do something like that:我会做这样的事情:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM