TypeScript数组map替换字段后filter过滤去重OTHER项问题
代码问题定位
你的代码有3个核心错误,导致完全达不到预期效果:
map回调没有返回值:你只在回调里修改了account属性,没有return处理后的对象,map执行完会得到全是undefined的数组filter回调没有返回值:仅写了判断表达式、没有return判断结果,过滤逻辑完全不生效- 过滤逻辑完全错误:你写的
account.currency != 'OTHER'会把所有OTHER类型的对象全部删掉,和「保留1个OTHER对象、移除重复OTHER」的需求完全相反 - 额外语法问题:你贴的原始
accounts数组里,第一个对象和第二个对象之间漏了逗号,会直接报语法错误
修正后可运行代码
// 补全原始数据缺失的逗号,避免语法报错 const mainCurrencies: string[] = ['GBP','EUR'] const accounts: AccountDetail[] = [ {currency:'GBP',date:'20/06/2022'}, {currency:'EUR',date:'20/06/2022'}, {currency:'CAD',date:'20/06/2022'}, {currency:'ZAR',date:'20/06/2022'} ] // 标记是否已经保留过OTHER类型对象 let hasReservedOther = false const processedAccounts = accounts .map(account => { // 用浅拷贝避免修改原始数组的对象,消除副作用 if (mainCurrencies.includes(account.currency)) { return { ...account } } return { ...account, currency: 'OTHER' } }) .filter(account => { // 所有主币种对象全部保留 if (account.currency !== 'OTHER') { return true } // 第一个遇到的OTHER对象保留,后续所有OTHER全部过滤 if (!hasReservedOther) { hasReservedOther = true return true } return false })
运行结果
执行后processedAccounts的输出完全符合需求:
[ {currency: 'GBP', date: '20/06/2022'}, {currency: 'EUR', date: '20/06/2022'}, {currency: 'OTHER', date: '20/06/2022'} ]
内容的提问来源于stack exchange,提问作者Thapelo Radebe
相关产品推荐
相关产品推荐

