I'm attempting to transpose a query result into a matrix. Essentially if I had this result:
| Attribute1 | Val | Count |
|---|---|---|
| Apples | Val 1 | 100 |
| Bananas | Val 1 | 200 |
| Apples | Val 2 | 300 |
| Bananas | Val 2 | 400 |
I want to transpose it to this:
| Attribute1 | Val 1 | Val 2 |
|---|---|---|
| Apples | 100 | 300 |
| Bananas | 200 | 400 |
However the number of values in the Attribute field & Val field are dynamic. How would I therefore go about transposing this in JS so my output JSON array is a dynamic structure dependent on the query result?
I've got a code snippet below where I've listed out the distinct [Attribute1] & [Val], but how do I build a json array where the definition is dynamic? I've made a stab at it at the end, but I know it's not right yet...
var res = [{
"Attribute1": 'Apples',
"Val": 'Val 1',
"Count": 100
},
{
"Attribute1": 'Bananas',
"Val": 'Val 1',
"Count": 200
},
{
"Attribute1": 'Apples',
"Val": 'Val 2',
"Count": 300
},
{
"Attribute1": 'Bananas',
"Val": 'Val 2',
"Count": 400
}
]
const y_result = [];
const map = new Map();
for (const item of res) {
if (!map.has(item.Attribute1)) {
map.set(item.Attribute1, true); // set any value to Map
y_result.push({
Attribute1: item.Attribute1,
});
}
}
console.log(y_result)
const x_result = [];
const x_map = new Map();
for (const item of res) {
if (!x_map.has(item.Val)) {
x_map.set(item.Val, true); // set any value to Map
x_result.push({
Attribute1: item.Val,
});
}
}
console.log(x_result)
let tmp
let new_res
console.log(y_result[0].Attribute1)
for (const item of y_result) {
tmp = { y_result[0].Attribute1 : item.Count };
new_res.push(tmp)
}
console.log(new_res)