Combining arrays for use cases

后端 未结 3 1712
再見小時候
再見小時候 2021-01-06 23:13

Node.js app, writing validation tests. Given the following:

var obj = { foo: null, bar: null, baz: null},
    values = [ 0, 1];

I need to

3条回答
  •  佛祖请我去吃肉
    2021-01-07 00:09

    Solution for any object length and any values.

    Please note, undefined values do not show up.

    function buildObjects(o) {
        var keys = Object.keys(o),
            result = [];
    
        function x(p, tupel) {
            o[keys[p]].forEach(function (a) {
                if (p + 1 < keys.length) {
                    x(p + 1, tupel.concat(a));
                } else {
                    result.push(tupel.concat(a).reduce(function (r, b, i) {
                        r[keys[i]] = b;
                        return r;
                    }, {}));
                }
            });
        }
    
        x(0, []);
        return result;
    }
    
    document.write('
    ' + JSON.stringify(buildObjects({
        foo: [0, 1, 2],
        bar: [true, false],
        baz: [true, false, 0, 1, 42]
    }), 0, 4) + '
    ');

提交回复
热议问题