[Solved] Restructure Javascript Object by grouping and Cartesian product


First, create an object using the given data and collect the keys and their values.

{
    A: [1, 2],
    C: ["FOO", "BAR"]
}

Then, get the Cartesian product of this object.

The function getCartesian separates all key/value pairs and builds a new Cartesian product by iterating over the values, if an array with objects call getCartesian again, and builds new objects.

This works for nested objects as well.

The algorithm is pretty simple, because it takes any property with a value, not just an array or object, and keeps this value and iterates over all other properties, which are arrays or objects. This algorithm keeps the inner structure and takes only the primitive values as result value for the given structure.

At the beginning, it takes an object/array, gets all entries and iterates them using an array with an empty object.

An empty array temp is the new result.

For creating new elements, the accumulator r is iterated and new values are collected. This is the part where the first level of a Cartesian product is made.

For a deeper level, a value is checked as well as “if an object”, then a recursive call is made and the new result is taken for the actual key.

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 data = { Values: [{ fieldValue: 1, fieldName: "A" }, { fieldValue: 2, fieldName: "A" }, { fieldValue: "FOO", fieldName: "C" }, { fieldValue: "BAR", fieldName: "C" }] },
    temp = data.Values.reduce((r, { fieldName, fieldValue }) => {
        (r[fieldName] = r[fieldName] || []).push(fieldValue);
        return r;
    }, {}),
    cartesian = getCartesian(temp);

console.log(cartesian);
.as-console-wrapper { max-height: 100% !important; top: 0; }

0

solved Restructure Javascript Object by grouping and Cartesian product