如何使用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
相关产品推荐
相关产品推荐

