简体   繁体   中英

Handling key-value pair in JQuery for charting

I have an ageband which I am generating with PHP from my database. The output is JSON-encoded and returned to my jQuery function.

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:

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

}

The key is the age-range, so for example, ages 20-19: 22 people etc.

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 )

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. 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 );
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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