Gui13
Gui13

Reputation: 13541

Flatten and merge array of array of objects in Javascript

Here is my input:

var toto=[
    [
        { "a": "24" },
        { "a": "23.9"},
        { "a": "NaN"},
        { "a": "3" }
    ],
    [
        {"b": "19"},
        {"b": "20"},
        {"b": "NaN"},
        {"b": "3" }
    ],
    [
        {"c": "27"},
        {"c": "28"},
        {"c": "NaN"},
        {"c": "3" }
    ]
];

All arrays of objects are guaranteed to contain the same number of objects.

I would like to obtain in output:

var out =  [
        { "a": "24", "b": "19", "c":"27" },
        { "a": "23.9", "b": "20", "c":"28"},
        { "a": "NaN", "b": "NaN", "c":"NaN"},
        { "a": "3", "b": "3", "c": "3"}
    ]

Which is, for each inner array, take the Nth element and merge it into an object, and push it into a result array.

I have a "braindead" solution which is iterating on the first sub-array and then iterating on the other arrays:

var out = [];
$(toto[0]).each(function(i, item) {
   var o = {};
   $(toto).each(function( j, array) {
    var item = array[i];
    o[Object.keys(item)[0]] = Object.values(item)[0];
   });
   out.push(o);
});

It works, but it is kind of hideous, and I would like to know if there's a solution using functional methods like map and reduce.

Do you guys know?

Upvotes: 2

Views: 298

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386550

You could use Array#reduce, Array#forEach and Object.assign for a pivot of the data with the same index for the inner array.

var toto=[[{ a: "24" }, { a: "23.9" }, { a: "NaN" }, { a: "3" }], [{ b: "19" }, { b: "20" }, { b: "NaN" }, { b: "3" }], [{ c: "27" }, { c: "28" }, { c: "NaN" }, { c: "3" }]],
    result = toto.reduce(function (r, a) {
        a.forEach(function (b, i) {
            r[i] = r[i] || {};
            Object.assign(r[i], b);
        });
        return r;
    }, []);

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

Upvotes: 6

Related Questions