Given the JSON response below:
const result = {
'potential': {
A: 514,
B: 3127,
C: 2970,
D: 282,
E: 41,
F: 1,
undefined: 48,
},
'current': {
A: 2,
B: 961,
C: 2897,
D: 2568,
E: 455,
F: 47,
G: 5,
undefined: 48,
},
};
I need to transform it to:
const temp = [
{ rating: 'A', potential: 514, current: 2 },
{ rating: 'B', potential: 3127, current: 961 },
{ rating: 'C', potential: 2970, current: 2897 },
{ rating: 'D', potential: 282, current: 2568 },
{ rating: 'E', potential: 41, current: 455 },
{ rating: 'F', potential: 1, current: 47 },
{ rating: 'G', potential: 0, current: 5 },
];
I manage by doing:
// Get unique list of keys
const allKeysSet = new Set(Object.keys(result).map(keys => Object.keys(result[keys])).flat().sort());
// Get feature names
const features = Object.keys(result);
const temp = [];
allKeysSet.forEach(s => {
// Get features object with corresponding values, if undefined return 0
const r = features.reduce((a, b) => ({ [a]: result[a][s] || 0, [b]: result[b][s] || 0 }));
temp.push( { reference: s, ...r} );
});
console.log(temp);
If there is a simpler/efficient way of doing this, I'll appreciate it.
undefined
key is included in the output, it is correct ? From the example you posted it seems me the keys are always equal inpotential
andcurrent
, it is always the expected scenario ? \$\endgroup\$Object.keys
andSet
s nets you, as you could useObject.entries
to cut out most of the code forreduce
. \$\endgroup\$