Aman Aman - 5 months ago 15
JSON Question

group by/formatting json data in Javascript

Sorry if this has been asked before. I have the JSON structure like:

{"data":[
{"Date":"03/04/2016","Key":"A","Values":"123"},
{"Date":"04/04/2016","Key":"A","Values":"456"},
{"Date":"03/04/2016","Key":"B","Values":"789"},
{"Date":"04/04/2016","Key":"B","Values":"012"}
]}


I want to change this to a different format which is basically grouped by Key and combines rest of the field in Values

{"Result":[
{
"Key":"A"
"Values":[["03/04/2016","123"], ["04/04/2016","456"]]
},
{"Key":"B"
"Values":[["03/04/2016","789"]},["04/04/2016","012"]]
}
]}


I want to do this javascript/html

Answer

You could iterate and build a new object if not exist.

var object = { "data": [{ "Date": "03/04/2016", "Key": "A", "Values": "123" }, { "Date": "04/04/2016", "Key": "A", "Values": "456" }, { "Date": "03/04/2016", "Key": "B", "Values": "789" }, { "Date": "04/04/2016", "Key": "B", "Values": "012" }], result: [] };

object.data.forEach(function (a) {
    if (!this[a.Key]) {
        this[a.Key] = { Key: a.Key, Values: [] };
        object.result.push(this[a.Key]);
    }
    this[a.Key].Values.push([a.Date, a.Values]);
}, Object.create(null));

console.log(object);