1

i use Angularjs. I have next data e.g:

let filters = {
                'async':[3,7],
                'gpu_freq':[400,500]
            };

Is there a better way to get the following combination then many loops?

[{
    'async': 3,
    'gpu_freq': 400
},{
    'async': 3,
    'gpu_freq': 50
},{
    'async': 7,
    'gpu_freq': 400
},{
    'async': 7,
    'gpu_freq': 500
}]

Number of filters can be different

Lola
  • 2,591
  • 6
  • 24
  • 49

1 Answers1

2

You could get a cartesian product by iterating the values, if an array with objects call getCartesian again and build new objects.

This works for nested objects as well.

function getCartesian(object) {
    return Object.entries(object).reduce((r, [k, v]) => {
        var temp = [];
        r.forEach(s =>
            (Array.isArray(v) ? v : [v]).forEach(w =>
                (w && typeof w === 'object' ? getCartesian(w) : [w]).forEach(x =>
                    temp.push(Object.assign({}, s, { [k]: x }))
                )
            )
        );
        return temp;
    }, [{}]);
}

var filters = { async: [3, 7], gpu_freq: [400, 500] },
    cartesian = getCartesian(filters);

console.log(cartesian);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392