I have an array of objects which I need to convert to a table (kind of pivoting the data). Saying this I need to get another array of objects with unique titles which have nested arrays of objects with pairs of the values then add the content vertically and horizontally. (Please refer to the image)
I have been able to generate an array of pivoted values but I will need to display them in a table and carry out some addition
Find here the Data
const data=[{
"Id": 1,
"Grade": "Grade A",
"category": "Grains",
"subCategory": "Maize",
"sales": 1200
},
{
"Id": 2,
"Grade": "Grade B",
"category": "Grains",
"subCategory": "Wheat",
"sales": 130
},
{
"Id": 3,
"Grade": "Grade B",
"category": "Grains",
"subCategory": "Banana",
"sales": 1200
},
{
"Id": 4,
"Grade": "Grade C",
"category": "Grains",
"subCategory": "Apple",
"sales": 1400
},
{
"Id": 5,
"Grade": "Grade A",
"category": "Grains",
"subCategory": "Maize",
"sales": 1200
},
{
"Id": 6,
"Grade": "Grade B",
"category": "Grains",
"subCategory": "Wheat",
"sales": 130
},
{
"Id": 7,
"Grade": "Grade B",
"category": "Grains",
"subCategory": "Banana",
"sales": 1200
},
{
"Id": 8,
"Grade": "Grade C",
"category": "Grains",
"subCategory": "Apple",
"sales": 1400
},
{
"Id": 7,
"Grade": "Grade B",
"category": "Grains",
"subCategory": "Banana",
"sales": 1200
},
{
"Id": 8,
"Grade": "Grade C",
"category": "Grains",
"subCategory": "Apple",
"sales": 1400
}]
let pivoted = data.reduce((prev, cur) => {
let existing = prev.find(x => x.title === cur.title);
if (existing)
existing.values.push(cur)
else
prev.push({
title: cur.title,
values: [cur]
});
return prev;
}, []);
console.log(pivoted);