learntech learntech - 3 months ago 13
Javascript Question

Transform structure of array of objects

I have data like -

var data = [{"DefaultZone":[{"key":"stream0","value":100},
{"key":"stream1","value":50},
{"key":"stream2","value":10}
]},
{"Zone 1":[{"key":"stream0","value":120},
{"key":"stream1","value":55},
{"key":"stream2","value":15}
]}
]


and wanted to transform it like -

var data = [{"key": "stream0", "values":[{"x":"DefaultZone","y":100}, {"x":"Zone 1","y":120}]},
{"key": "stream1", "values":[{"x":"DefaultZone","y":50}, {"x":"Zone 1","y":55}]},
{"key": "stream2", "values":[{"x":"DefaultZone","y":10}, {"x":"Zone 1","y":15}]}
];


using JavaScript(ES6). Any help would be highly appreciated..

Answer

Here is the first way that came to mind:

var data = [{
  "DefaultZone": [
    { "key": "stream0", "value": 100 },
    { "key": "stream1", "value": 50 },
    { "key": "stream2", "value": 10 }]
}, { 
  "Zone 1": [
    { "key": "stream0", "value": 120 },
    { "key": "stream1", "value": 55 },
    { "key": "stream2", "value": 15 }]
}];

let working = data.reduce((p, c) => {
  let x = Object.keys(c)[0];
  c[x].forEach(v => {
    if (!p[v.key]) p[v.key] = [];
    p[v.key].push({ x: x, y: v.value });
  });
  return p;
}, {});

let output = Object.keys(working).map(v => ({ key: v, values: working[v] }));

console.log(output);

Further reading: