简体   繁体   中英

d3.js chart from json object

I'd like to create a simple pie chart in d3.js. The request response that I'm working with looks like this:

{"record":[{"status":"request"},{"status":"requirements"},{"status":"request"}]};

From what I've seen in examples, I need to convert that object to this:

[{"label":"Request", "value":2}, {"label":"Requirements", "value":1}];

I'm happy to use d3 functions or underscore or straight javascript to accomplish this, I just haven't been able to crack it on my own. Any help would be much appreciated!

You can use d3.nest() to reformat your data:

var data = d3.nest()
    .key(function(d){ return d.status; })
    .rollup(function(leaves){ return leaves.length; })
    .entries(input.record)
    .map(function(d){ return {label: d.key, value: d.values}; });

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