这里我有这样的数据,
var dataArray = '[{"name":"books","value":43},{"name":"DVDs","value":99},{"name":"Magazines","value":37},{"name":"eBooks","value":88},{"name":"Other awesome things","value":67}]';
我想动态地使用此数据构建此chart
,这意味着我的json
在实际项目中会很大,来自database
。
这里是我想要的chart
的jsfiddle(动态地为我的情况):http://jsfiddle.net/artefactory/m4on9L4p/
//canvasJS example - doughnut chart showing collection breakdown.
var dataArray = '[{"name":"books","value":43},{"name":"DVDs","value":99},{"name":"Magazines","value":37},{"name":"eBooks","value":88},{"name":"Other awesome things","value":67}]';
window.onload = function () {
var chart = new CanvasJS.Chart("chartContainer",
{
title:{
text: "What's in our collection"
},
data: [
{
type: "doughnut",
// how to substitute above array here
dataPoints: [
{ y: 53.37, indexLabel: "Books" },
{ y: 35.0, indexLabel: "DVDs" },
{ y: 7, indexLabel: "Magazines" },
{ y: 2, indexLabel: "eBooks" },
{ y: 5, indexLabel: "Other awesome things" }
]
}
]
});
chart.render();
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/canvasjs/1.4.1/canvas.min.js"></script>
<div id="chartContainer" style="height: 300px; width: 100%;"> </div>
&#13;
我想建立这个
dataPoints: [
{ y: 53.37, indexLabel: "Books" },
{ y: 35.0, indexLabel: "DVDs" },
{ y: 7, indexLabel: "Magazines" },
{ y: 2, indexLabel: "eBooks" },
{ y: 5, indexLabel: "Other awesome things" }
]
动态地使用我的json。我怎么能这样做?
问题而不是使用hardcoded
值,我想使用json
来构建图表?
答案 0 :(得分:5)
使用JSON.parse()
和Array.prototype.map()
函数的解决方案:
...
dataPoints: JSON.parse(dataArray).map(function (o) {
return {y: o.value, indexLabel: o.name};
})
...
答案 1 :(得分:0)
值53.37,35.0是如何得出的?是否有推导的数学公式?
如果你只是将“names”映射到indexLabel而将“value”映射到x,那么这段代码应该可以工作。
var desiredObj = x.map(function(currentElement) {return {x: currentElement.value, indexLabel: currentElement.name}});
答案 2 :(得分:0)
你可以像这样使用jQuery maop函数:
var myNewDataArray = $.map(dataArray,function(a,b){
return {
y : a.value,
indexLabel : a.name
}
});