注意:该问题与其他排列问题不同,因为它是对象数组,而不是整数数组。
我有一个这样的对象数组:
var options =
[
{
name: "Size",
choices: [
{
label: "Small",
price: 0
},
{
label: "Medium",
price: 10
}
]
},
{
name: "Color",
choices: [
{
label: "Yellow",
price: 0
},
{
label: "Purple",
price: 10
}
]
}
]
我想创建一个函数,将所有可能的变化生成到这样的对象中:
{
"Size-Small--Color-Yellow": {
label: "Size: Small, Color: Yellow",
choices: {
Size: {
label: "Small",
price: 0
},
Color: {
label: "Yellow",
price: 0,
}
},
},
"Size-Small--Color-Purple": {
label: "Size: Small, Color: Purple",
choices: {
Size: {
label: "Small",
price: 0
},
Color: {
label: "Purple",
price: 10,
}
},
},
"Size-Medium--Color-Yellow": {
label: "Size: Medium, Color: Yellow",
choices: {
Size: {
label: "Medium",
price: 10
},
Color: {
label: "Yellow",
price: 0,
}
},
},
"Size-Medium--Color-Purple": {
label: "Size: Medium, Color: Purple",
choices: {
Size: {
label: "Medium",
price: 10
},
Color: {
label: "Purple",
price: 10,
}
},
}
}
对象的实际数组要大得多,其中包含更多选项和选择,因此,解决方案需要使用各种数组大小,从像这样的小数组到非常大的选项集。 < / p>
这是我到目前为止尝试过的:
function generateVariations() {
var variations = {};
for(var i in options) {
var option = options[i];
var key = '';
var keyArray = [];
for(var j in option.choices) {
var choice = option.choices[j];
console.log(choice, 'choice value');
keyArray.push(option.name + '-' + choice.label)
}
key = keyArray.join('--');
console.log(key, 'key made for object');
variations[key] = {}; // TODO: After generating all of the keys, assign them correct values.
}
return variations;
}
我无法绕过递归方面,因为可能会有无限数量的变体,不确定是否需要递归。
答案 0 :(得分:1)
使用递归可能是这里最优雅的方法,我将使用生成器函数,因为您可以逐步生成值,如果有无限多个组合,该函数也将起作用:
function* combine(options, index = 0, previous = {}) {
if(index >= options.length) yield previous;
const { name, choices } = options[index];
for(const { label, price } of choices) {
yield* combine(options, index + 1, { ...previous, [name]: { label, price }});
}
}
可用作:
for(const combo of combinations(options))
console.log(combo);