如何在JavaScript中比较关联对象数组的账户余额和是否为零?
解决方案
核心思路
要实现需求,关键是建立双向关联的快速查找映射,同时保证遍历顺序和所有银行账户的顺序一致:
- 先把所有平台按ID存为映射,方便通过ID直接获取平台对象;
- 按顺序收集所有银行账户,并记录每个账户所属的平台ID;
- 对每个账户,通过其
lendingPlatformId找到目标平台,再在目标平台中找到反向关联(lendingPlatformId等于当前账户所属平台ID)的账户,最后计算余额和是否为0。
代码实现(JavaScript)
const platforms = [ { "id": 1, "name": "KF", "bankAccounts": [ { "id": 22, "balance": -100, "lendingPlatformId": 3 }, { "id": 27, "balance": 500, "lendingPlatformId": 4 } ] }, { "id": 3, "name": "CC", "bankAccounts": [ { "id": 23, "balance": 100, "lendingPlatformId": 1 } ] }, { "id": 4, "name": "DD", "bankAccounts": [ { "id": 28, "balance": 0, "lendingPlatformId": 1 } ] } ]; // 1. 建立平台ID到平台对象的映射 const platformMap = platforms.reduce((map, platform) => { map[platform.id] = platform; return map; }, {}); // 2. 按顺序收集所有银行账户,并附带所属平台ID const allBankAccounts = []; platforms.forEach(platform => { platform.bankAccounts.forEach(account => { allBankAccounts.push({ ...account, ownerPlatformId: platform.id }); }); }); // 3. 遍历计算每个账户的匹配结果 const isEqualToZero = allBankAccounts.map(account => { const targetPlatform = platformMap[account.lendingPlatformId]; // 找到目标平台中反向关联的账户 const matchedAccount = targetPlatform.bankAccounts.find(ba => ba.lendingPlatformId === account.ownerPlatformId); // 判断余额和是否为0(假设matchedAccount一定存在,若需容错可加判断) return account.balance + matchedAccount.balance === 0; }); console.log(isEqualToZero); // 输出: [true, false, true, false]
为什么你的原映射无法实现需求
你之前构建的映射只记录了平台ID对应的lendingPlatformId和余额,但没有建立双向关联的查找路径——比如无法通过platformId=3的lendingPlatformId=1,快速找到platformId=1中lendingPlatformId=3的账户。而上面的方案通过平台映射+反向查找,解决了这个问题,同时严格保证了遍历顺序和结果顺序一致。
内容的提问来源于stack exchange,提问作者user19304185
相关产品推荐
相关产品推荐

