You need to enable JavaScript to run this app. 如何根据扁平选项数据修改JavaScript对象的options属性值
优惠活动
大模型
产品
解决方案
定价
更多

如何根据扁平选项数据修改JavaScript对象的options属性值

基于扁平变体列表更新原属性配置的options

完全可以实现,全程不需要复杂递归,两步就能得到目标结构:

  1. 从拆解后的扁平变体数组中,提取每个属性维度下实际出现过的选项值,去重后生成「属性名→有效选项列表」的映射关系
  2. 遍历原始属性配置数组,匹配对应属性名,将原有的全量options替换为映射表中存储的、实际出现过的选项集合

可直接复用的实现代码

// 原始属性配置数组
const originConfig = [
  {
    id: 0,
    name: "Weight",
    options: ["250gr", "500gr"],
    position: 0,
    variation: true,
    visible: true
  },
  {
    id: 0,
    name: "Roast",
    options: ["Light", "Medium", "Dark"],
    position: 0,
    variation: true,
    visible: true
  },
  {
    id: 0,
    name: "Packaging",
    options: ["Tin", "Card"],
    position: 0,
    variation: true,
    visible: true
  }
]

// 拆解后的扁平变体数据
const flatVariants = [
  {id: 0, name: "Weight", option: "250gr"},
  {id: 0, name: "Roast", option: "Medium"},
  {id: 0, name: "Packaging", option: "Card"},
  {id: 0, name: "Weight", option: "250gr"},
  {id: 0, name: "Roast", option: "Light"},
  {id: 0, name: "Packaging", option: "Card"}
]

// 步骤1:构建属性名与去重选项的映射
const optionMap = flatVariants.reduce((map, item) => {
  if (!map[item.name]) map[item.name] = new Set()
  map[item.name].add(item.option)
  return map
}, {})

// 步骤2:遍历原配置生成目标结构
const targetConfig = originConfig.map(configItem => {
  configItem.options = Array.from(optionMap[configItem.name] || [])
  return configItem
})

实现效果

输出的targetConfig完全匹配要求的目标结构:

  • Weight的options仅保留实际使用过的"250gr",移除未被用到的"500gr"
  • Roast的options保留实际使用过的"Light"、"Medium",移除未被用到的"Dark"
  • Packaging的options仅保留实际使用过的"Card",移除未被用到的"Tin"

适配细节

  • 代码中使用Set做选项去重,避免同一变体重复出现时重复写入相同的option值
  • 如果存在某类属性在扁平变体中完全没记录的场景,可修改options赋值逻辑为:
    configItem.options = optionMap[configItem.name] 
      ? Array.from(optionMap[configItem.name]) 
      : configItem.options
    
    这类无对应变体记录的属性会保留原有options值,不会被清空为空数组。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.13 20:45:04