Cartesian product of javascript object properties

半世苍凉 提交于 2019-12-04 06:06:37

Ok, let's start with a function that generates a product of given arrays:

function product(args) {
    if(!args.length)
        return [[]];
    var prod = product(args.slice(1)), r = [];
    args[0].forEach(function(x) {
        prod.forEach(function(p) {
            r.push([x].concat(p));
        });
    });
    return r;
}

The next one uses product to convert something like {a:[1,2], b:[3,4]} into [{a:1,b:3},{a:1,b:4},{a:2,b:3},{a:2,b:4}]:

function objectProduct(obj) {
    var keys = Object.keys(obj),
        values = keys.map(function(x) { return obj[x] });

    return product(values).map(function(p) {
        var e = {};
        keys.forEach(function(k, n) { e[k] = p[n] });
        return e;
    });
}

For your test data, you have to apply it twice:

var result = {};
Object.keys(test).forEach(function(k) {
    result[k] = objectProduct(test[k])
});

result = objectProduct(result);

This gives you the output you wanted.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!