Reputation: 352
I have a JSON object containing array datas which holds the data I want to use to produce my chart. I want to use the data1 array for the x-axis using the category format. How can I do that ?
This is what I tried, which is copying the data out of the JSON object into a string:
chsrt script
var datas={"data1":["a","b"],"data2":["10","20"]};
// this come from ajax
var out ="";
for(var i=0;i<datas.data1.length;i++){
var out = datas.data1[i];
}
alert(out);
var chart = c3.generate({
bindto: '#chart',
size: {
height: 450,
},
data: {
columns: [
['data1', 30, 200, 100, 400, 150, 250],
['data2', 50, 20, 10, 40, 15, 25]
],
type: 'line',
},
color: {
pattern: ['#80B5EC', '#2A2A2E', '#FC8D2D', '#3FE51D', '#F51E50', '#F5D81E', '#d62728', '#ff9896', '#9467bd', '#c5b0d5', '#8c564b', '#c49c94', '#e377c2', '#f7b6d2', '#7f7f7f', '#c7c7c7', '#bcbd22', '#dbdb8d', '#17becf', '#9edae5']
},
zoom: {
enabled: true
},
axis: {
x: {
type: 'category',
tick: {
multiline: false
},
categories: [out],
height: 100
},y: {
label:{
text:'TASKS',
position: 'outer-middle'
}
}
},
grid:{
y:{
show:true
}
}
});
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/c3/0.6.8/c3.js"></script>
<div id="chart"></div>
alert out put is:
a,b
if i use i this var out in c3.js object i thing it will came like "a,b"
or ['a,b']
how can i get this value in c3.js object.chart out put image here
Upvotes: 0
Views: 967
Reputation: 9535
Here is a cut-down cleaned up version of your code. You will see that you can refer to the data1 variable from within the JSON object without needing to extract the data.
What your JS did in the for loop was assign the value of the data1 array to a string, causing the Array.toString() built in function to fire and concatenate the array members into a string. There are plenty of examples on the web of how to copy arrays. However, as I have said, you do not need to do this because you can access the array direct form the JSON object.
EDIT: The snippet has been modified to be a more representative sample where the data set to be plotted is delivered within the JSON. Here we use Array.unshift to place the data set name into the column array.
var data = {"datapts":["a","b","c","d","e","f"], "data1": [30, 200, 100, 400, 150, 250]};
// Arr,ay.unshift inserts an entry at the start of an array.
data.data1.unshift('data1');
var chart = c3.generate({
data: {
columns: [
data.data1
],
type: 'line'
},
axis: {
x: {
type: 'category',
categories: data.data1
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/c3/0.6.8/c3.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/c3/0.6.8/c3.min.js"></script>
<div class='wrapper' style='height: 450px;'>
<div id="chart"></div>
</div>
Upvotes: 1