Emil Gurbanov Emil Gurbanov - 28 days ago 16
Javascript Question

How Do I Pivot An Array Of Objects in JavaScript?

I have an array of object which I need to convert to a table (kind of pivoting the data). Saying this I need to get another array of objects with the unique titles which have nested arrays of object with pairs of the values. Could you please take a look into this and help with achiving what I need? Please see the original and the desired array below:

Original Array:

[
{title: "Title1", value1: "value1", value2: "value2"},
{title: "Title2", value1: "value1", value2: "value2"},
{title: "Title1", value1: "value1", value2: "value2"},
{title: "Title3", value1: "value1", value2: "value2"},
{title: "Title2", value1: "value1", value2: "value2"},
{title: "Title1", value1: "value1", value2: "value2"},
{title: "Title3", value1: "value1", value2: "value2"},
{title: "Title1", value1: "value1", value2: "value2"},
]


Desired result:

[
{title: "Title1", values: [{value1: "value1"}, {value2: "value2"}]},
{title: "Title2", values: [{value1: "value1"}, {value2: "value2"}]},
{title: "Title3", values: [{value1: "value1"}, {value2: "value2"}]},
]


Thanks if advance for any suggestions.

Answer

You could use a hash table for grouping as thisArg with Array#forEach.

var data = [{ title: "Title1", value1: "value1", value2: "value2" }, { title: "Title2", value1: "value1", value2: "value2" }, { title: "Title1", value1: "value1", value2: "value2" }, { title: "Title3", value1: "value1", value2: "value2" }, { title: "Title2", value1: "value1", value2: "value2" }, { title: "Title1", value1: "value1", value2: "value2" }, { title: "Title3", value1: "value1", value2: "value2" }, { title: "Title1", value1: "value1", value2: "value2" }],
    grouped = [];

data.forEach(function (a) {

    // check if title is not in hash table
    if (!this[a.title]) {

        // if not, create new object with title and values array
        // and assign it with the title as hash to the hash table
        this[a.title] = { title: a.title, values: [] };

        // add the new object to the result set, too
        grouped.push(this[a.title]);
    }

    // create a new object with the other values and push it
    // to the array of the object of the hash table
    this[a.title].values.push({ value1: a.value1, value2: a.value2 });
}, Object.create(null)); // Object.create creates an empty object without prototypes

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