javascript - 从约束列表中生成所有可能的对象

标签 javascript algorithm

<分区>

我正在尝试从约束哈希生成所有可能的对象。

假设约束是:

{
    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/

相关文章:

javascript - 如何使用 Jquery 绑定(bind)菜单和子菜单应用 css?

c++ - kd-tree 中的无限递归

algorithm - 最小转弯的 A 星优化

algorithm - 这个作业最快的算法是什么?

javascript - 单击后类之间的内容如何放入变量?

javascript - 根据 javascript confirm 的响应退出 php 脚本

javascript - 从 url(adwords 着陆页)触发嵌入式 Javascript

Javascript 函数删除和替换

c++ - 如何将非常大的十进制数转换为阶乘数系统?

c# - A*寻路..保存路径