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

如何使用JavaScript生成多个属性对象的所有属性值可选组合

JavaScript 生成产品属性全组合方案

直接上可直接运行的实现代码:

function generateAttrCombinations(attrArray) {
  let result = [[]]
  for (const { name, options } of attrArray) {
    const temp = []
    for (const existingCombination of result) {
      for (const opt of options) {
        temp.push([...existingCombination, { name, value: opt.value }])
      }
    }
    result = temp
  }
  return result
}

使用示例

输入结构和你提供的结构一致即可:

const input = [
  {
    name: "尺寸",
    options: [ { value: "S" }, { value: "M" }, { value: "L" }]
  },
  {
    name: "颜色",
    options: [ { value: "红" }, { value: "白" }, { value: "蓝" }]
  },
  {
    name: "重量",
    options: [ { value: "1kg" }, { value: "2kg" }, { value: "3kg" }, { value: "4kg"}]
  }
]

// 得到的output就是你要求的格式
const output = generateAttrCombinations(input)

这个实现采用迭代方式生成笛卡尔积,不管输入的属性有多少个、每个属性的可选值有多少个,都能正确输出所有可能的属性组合,输出格式完全符合要求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 16:54:06