Transposing JSON Object using Google Apps Script

Gists

This is a sample script for transposing JSON object using Google Apps Script.

Input data :

[
    {"key1":"a1","key2":"a2","key3":"a3","key4":"a4","key5":"a5"},
    {"key1":"b1","key2":"b2","key3":"b3","key4":"b4","key5":"b5"},
    {"key1":"c1","key2":"c2","key3":"c3","key4":"c4","key5":"c5"},
    {"key1":"d1","key2":"d2","key3":"d3","key4":"d4","key5":"d5"},
    {"key1":"e1","key2":"e2","key3":"e3","key4":"e4","key5":"e5"}
]

Output data :

{
    "key1": ["a1", "b1", "c1", "d1", "e1"],
    "key2": ["a2", "b2", "c2", "d2", "e2"],
    "key3": ["a3", "b3", "c3", "d3", "e3"],
    "key4": ["a4", "b4", "c4", "d4", "e4"],
    "key5": ["a5", "b5", "c5", "d5", "e5"]
}

Script :

At first, keys have to be defined by yourself, because the order of json is not decided.

var keys = ["key1", "key2", "key3", "key4", "key5"];
var result = {};
data.map(function(_, i){return keys.map(function(f, j){return data[i][keys[j]]})}).forEach(function(e, i){result[keys[i]] = e});
Logger.log(JSON.stringify(result))

 Share!