You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript中如何按条件为对象数组增删键值对 可否用map单行实现

问题解答

完全可以用map方法单行实现需求,根据是否需要保留原始数组数据,有两种实现方案:

方案1:不修改原数组(无副作用,推荐)

该方案通过对象解构生成新对象,不会改动原始数组内的任何对象,符合map方法的纯函数使用规范:

const result = this.data.object.map(item => item.dealType === 'PM Restructure' ? {...item, cashContribution: 3000, storeCashFlow: 4000} : item.dealType === 'Partner Location Submission' ? (({annualRentProposed, annualRentCurrent, ...rest}) => rest)(item) : {...item})

方案2:允许修改原数组内的对象(写法更简洁)

该方案利用逗号运算符,在同一个表达式内完成属性修改/删除操作后直接返回原对象,会改动原始数组中的对象:

const result = this.data.object.map(item => (item.dealType === 'PM Restructure' && Object.assign(item, {cashContribution: 3000, storeCashFlow: 4000}), item.dealType === 'Partner Location Submission' && (delete item.annualRentProposed, delete item.annualRentCurrent), item))

两种写法均严格匹配给出的规则,处理后的数据可以直接赋值使用。


内容的提问来源于stack exchange,提问作者Brinda Anand

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 07:24:05