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

JavaScript如何结合default属性过滤id_combination重复的产品项

JavaScript 产品组合数组去重实现方案

核心规则对齐

处理逻辑完全匹配需求:

  • 按id_combination字段去重,下拉框不展示重复选项
  • 同一id_combination分组下,优先保留default: true的条目作为默认选中项
  • 分组下无default: true条目时,自动保留1条普通条目,保证选项不缺失
  • 全程不修改后端返回的原始数据

实现代码

用Map做单次遍历即可完成处理,时间复杂度O(n),性能最优:

function processCombinationList(rawArray) {
  const combinationStore = new Map();
  for (const item of rawArray) {
    const comboId = item.id_combination;
    // 同id首次出现直接存入,保证无默认项时也有保留条目
    if (!combinationStore.has(comboId)) {
      combinationStore.set(comboId, item);
      continue;
    }
    // 遍历到同id的默认项时,覆盖之前存储的非默认条目
    if (item.default === true) {
      combinationStore.set(comboId, item);
    }
  }
  return Array.from(combinationStore.values());
}

使用示例

// 后端返回的原始数据
const rawData = [
  {'id_combination': 15, 'default': false},
  {'id_combination': 20, 'default': false},
  {'id_combination': 30, 'default': false},
  {'id_combination': 30, 'default': true},
  {'id_combination': 45, 'default': false}
];

const dropdownOptions = processCombinationList(rawData);
// dropdownOptions即可直接传入select组件作为选项使用

逻辑说明

  • 首次遍历到某id_combination时直接存储,从根源上保证无默认项的分组至少有1条可展示数据
  • 后续遍历到同id条目时,仅当条目为default: true才覆盖原有存储值,保证默认项优先级最高
  • 原始数组全程不会被修改,仅生成新的处理后数组,符合不可修改后端返回数据的要求
  • 若同id下存在多条default: true的异常数据,会保留最后遍历到的默认项,兼容异常返回场景

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 16:42:58