I have the following JSON:
[
{
"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"
}
]
I have a function that loops over the objects in the array and then loops over the properties/keys of that object and attempts to make and push properties damage through class6 of each object to its own new object and onto chart.data.datasets array. I'm getting 16 values in each objects data array instead of the desired 8.
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) {
//console.log(`Value: ${data[i][property]}`);
myData.data.push(item[property]);
}
console.log(`Property: ${property}, Value: ${item[property]}`);
count++;
}
myData.label = data[i].name;
myChart.data.datasets.push(myData);
});
//myChart.data.datasets[0].highlightStroke = "";
console.log(myChart.data.datasets);
}
The problem here is that you are trying to create deep copy of dataset
variable using Object.create
. It does not create deep copy and all copies will share one single instance of data
array. As a quick dirty fix you can instead use Object.assign({}, dataset, {data: []})