简体   繁体   English

在JQuery中处理键值对以进行图表制作

[英]Handling key-value pair in JQuery for charting

I have an ageband which I am generating with PHP from my database. 我有一个年龄段,该年龄段是通过数据库从PHP中生成的。 The output is JSON-encoded and returned to my jQuery function. 输出经过JSON编码,并返回到我的jQuery函数。

The data returned looks like this: 返回的数据如下所示:

{"result":{"20 - 29":"22","30 - 39":"78","40 - 49":"74","50 - 59":"71","60 - 69":"67","70 & Older":"0","Not Filled In (NULL)":"0"},"errors":false}

I am fetching this data using AJAX/jQuery: 我正在使用AJAX / jQuery获取此数据:

if(!response.errors && response.result) {

}

The key is the age-range, so for example, ages 20-19: 22 people etc. 关键是年龄范围,例如20-19岁:22人等。

Anyway, I am trying to use the data to create a pie-chart, i'm using echarts ( https://ecomfe.github.io/echarts/index-en.html ) 无论如何,我正在尝试使用数据创建一个饼图,我正在使用echarts( https://ecomfe.github.io/echarts/index-en.html

The data format with sample data looks like this: 带有样本数据的数据格式如下所示:

data: [{ value: 12, name: 'Moto Z' },{ value: 618, name: 'Galaxy S7 Edge' }]

I want my data to show like this: 我希望我的数据显示如下:

data: [{ value: 22, name: '20-29' },{ value: 78, name: '30-39' }... etc]

How can I use my returned data with this chart? 如何将返回的数据与此图表一起使用?

You need to loop through your object. 您需要遍历对象。

var data = []
$.each( result, function( key, value ) {
  data.push({ value: value, name: key })
});

Result is the contents of the result object in your Ajax response. 结果是Ajax响应中结果对象的内容。 The new 'data' variable should be formatted per your needs. 新的“数据”变量应根据您的需要进行格式化。

If you don't mind using another external library like underscore then: 如果您不介意使用下划线之类的其他外部库,则:

var data = _( _.pairs( json['result'] ) ).map( function(val) {
  return _.object( ['name', 'value'], val );
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM