I have an object that contains multiple datasets objects that can contain an array of items or multiple arrays within this object. Without knowing whether it is a multiple object array, how can I pass it to function, that is expecting to 'forEach' depending on the amount of the arrays?
To make it more clear see data within storage:
var storage = {
dataset1: {
labels: ["Mon", "Tue", "Wed"],
storageDatasets: [{ // two objects here
data: [2, 4, 5, 6, 10]
},
{
data: [200, 100, 300, 600]
}
]
},
dataset2: {
labels: ["Mon", "Tue", "Wed"],
storageDatasets: [{ // one object here
data: [200, 100, 300, 600]
}]
}
};
with above I am trying to pass them as parameters:
$(".change").click(function() {
var temp = $(this).text();
addChartData(myChart, storage[temp].labels, storage[temp].storageDatasets.data); // how to get last parameter correctly, based on the amount of data objects?
});
and process using this function:
function addChartData(chart, labels, data) {
chart.data.labels = labels;
chart.data.datasets.forEach(dataset => {
dataset.data = data;
});
chart.update();
}
The problem is with the amount of data objects within storageDatasets in var storage. Some will have multiple, some one. How can I loop through them to pass them as argument so addChartData function will run correctly.
var config = {
type: 'line',
data: {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [{
label: "My First dataset",
data: [65, 0, 80, 81, 56, 85, 40],
fill: false
}]
}
};
var storage = {
dataset1: {
labels: ["Mon", "Tue", "Wed"],
storageDatasets: [{
data: [2, 4, 5, 6, 10]
},
{
data: [200, 100, 300, 600]
}
]
},
dataset2: {
labels: ["Mon", "Tue", "Wed"],
storageDatasets: [{
data: [200, 100, 300, 600]
}]
}
};
function addChartData(chart, labels, data) {
chart.data.labels = labels;
chart.data.datasets.forEach(dataset => {
dataset.data = data;
});
chart.update();
}
var ctx = document.getElementById("myChart").getContext("2d");
var myChart = new Chart(ctx, config);
$(".change").click(function() {
var temp = $(this).text();
addChartData(myChart, storage[temp].labels, storage[temp].storageDatasets.data);
console.log(temp);
});
.chart-container {
height: 300px;
width: 500px;
position: relative;
}
canvas {
position: absolute;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.js"></script>
<div> <button class="change">dataset1</button></div>
<div> <button class="change">dataset2</button></div>
<div class="chart-container">
<canvas id="myChart"></canvas>
</div>
dataset.dataneed? for example, it needs this:[2, 4, 5, 6, 10, 200, 100, 300, 600]<---Concatenation.storageDatasetsto your function instead, and have it iterate through each childdataobject.