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

如何重构JavaScript条件数组对象中的重复属性?

重构方案

可以把重复的公共数组元素抽出来单独处理,再根据条件拼接额外元素,彻底消除重复代码:

方式一:抽取公共数组 + 扩展运算符拼接

const { address } = A;
// 提取重复的公共部分
const commonItems = [
  { text: text },
  { building: address },
  { ' ': pincode }
];
// 按条件组合最终数组
data: conditionalValue 
  ? commonItems 
  : [...commonItems, { 'somevalue': someValue1 }, { ' ': otherValue }],

方式二:直接在公共数组后条件追加元素

如果不想额外定义变量,也可以直接在公共数组后通过扩展运算符条件添加元素:

const { address } = A;
data: [
  { text: text },
  { building: address },
  { ' ': pincode },
  // 仅当条件不成立时追加额外元素
  ...(conditionalValue ? [] : [{ 'somevalue': someValue1 }, { ' ': otherValue }])
],

两种方式都能解决重复代码问题,第一种可读性更强,第二种更简洁,可根据你的代码风格选择。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 11:20:28