<分区>
我正在尝试从约束哈希生成所有可能的对象。
假设约束是:
{
key1: [ 'possible value1' , 'possible value2' ],
key2: [ 2, 4, 7, 1],
...
}
我想生成所有可能的对象:
{ key1: 'possible value1', key2: 2 }
{ key1: 'possible value1', key2: 4 }
...
任何人都可以指出我正确的方向吗?
谢谢!
<分区>
我正在尝试从约束哈希生成所有可能的对象。
假设约束是:
{
key1: [ 'possible value1' , 'possible value2' ],
key2: [ 2, 4, 7, 1],
...
}
我想生成所有可能的对象:
{ key1: 'possible value1', key2: 2 }
{ key1: 'possible value1', key2: 4 }
...
任何人都可以指出我正确的方向吗?
谢谢!
最佳答案
var options = {
key1: [ 'possible value1' , 'possible value2'],
key2: [ 2, 4, 7, 1],
key3: ['TEST1', 'TEST2']
};
function getCombinations(options, optionIndex, results, current) {
var allKeys = Object.keys(options);
var optionKey = allKeys[optionIndex];
var vals = options[optionKey];
for (var i = 0; i < vals.length; i++) {
current[optionKey] = vals[i];
if (optionIndex + 1 < allKeys.length) {
getCombinations(options, optionIndex + 1, results, current);
} else {
var res = JSON.parse(JSON.stringify(current));
results.push(res);
}
}
return results;
}
var results = getCombinations(options, 0, [], {});
document.body.innerHTML = JSON.stringify(results);
关于javascript - 从约束列表中生成所有可能的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43971480/