Skip to content Skip to sidebar Skip to footer

Flip Key Value Pair On 1 Lvl Depth

I have object: const pairs = { A: { D: [1, 2, 3] }, B: { D: [3, 2, 1] }, C: { D: [4, 3, 2, 1], B: [0, 1, 2, 3] } }; How can I get it fliped? const fliped = { D:

Solution 1:

You could take a nested approach by reducing the entries of the objects.

const
    pairs = { A: { D: [1, 2, 3] }, B: { D: [3, 2, 1] }, C: { D: [4, 3, 2, 1], B: [0, 1, 2, 3] } },
    result = Object
        .entries(pairs)
        .reduce((r, [right, object]) =>Object
            .entries(object)
            .reduce((r, [left, value]) => {
                r[left] = r[left] || {};
                r[left][right] = value;
                return r;
            }, r), {});

console.log(result);

Another approach is to use a recursive function by creating the properties after collecting all keys.

constreverse = (source, target = {}, keys = []) => {
        if (source && typeof source === 'object' && !Array.isArray(source)) {
            Object.entries(source).forEach(([k, v]) =>reverse(v, target, [k, ...keys]));
        } else {
            var last = keys.pop();
            keys.reduce((o, k) => o[k] = o[k] || {}, target)[last] = source;
        }
        return target;
    },
    pairs = { A: { D: [1, 2, 3] }, B: { D: [3, 2, 1] }, C: { D: [4, 3, 2, 1], B: [0, 1, 2, 3] } },
    result = reverse(pairs);

console.log(result);

Post a Comment for "Flip Key Value Pair On 1 Lvl Depth"