Here is the JSON data that I am working with:
[
{
"name": "sp5",
"damage": "68",
"penetration": "35",
"class1": "6",
"class2": "6",
"class3": "6",
"class4": "5",
"class5": "3",
"class6": "2"
},
{
"name": "sp6",
"damage": "58",
"penetration": "43",
"class1": "6",
"class2": "6",
"class3": "6",
"class4": "6",
"class5": "5",
"class6": "4"
}
]
In my function, I iterate over each object in the array and then loop through the properties of that object. The goal is to extract properties from 'damage' to 'class6' and create a new object for each item to be pushed onto the chart.data.datasets array. However, instead of having 8 values in each object's data array, I am ending up with 16.
function createObjectsForChart(data) {
console.log(`Data: ${data}`);
const chart = {
type: 'bar',
data: {
labels: ["Damage", "Penetration", "Class1", "Class 2", "Class 3", "Class 4", "Class 5", "Class 6"],
datasets: [],
}
}
const dataset = {
label: "",
fillColor: "rgba(220,220,220,0.5)",
strokeColor: "rgba(220,220,220,0.8)",
highlightFill: "rgba(220,220,220,0.75)",
highlightStroke: "rgba(220,220,220,1)",
data: []
}
let myChart = Object.create(chart);
data.forEach((item, i) => {
console.log(`Item: ${item}, Index: ${i}`);
console.log(`Data length: ${data.length}`);
//data[i]
let myData = Object.create(dataset);
count = 0;
for (const property in item) {
if(count >= 1) {
myData.data.push(item[property]);
}
console.log(`Property: ${property}, Value: ${item[property]}`);
count++;
}
myData.label = data[i].name;
myChart.data.datasets.push(myData);
});
console.log(myChart.data.datasets);
}