如何映射数据,以便我可以用它来生成饼图?

时间:2012-12-28 03:28:07

标签: node.js express d3.js

我想知道如何映射2个数组的数据,这样我就可以使用数据来生成使用d3.js的图表

目前我有2个阵列:

wordsArray = {"THE","MAIN","PURPOSE","OF","PHOTOSYNTHESIS","IS","TO","MAKE",
             "FOOD","FOR","PLANT","IT","PRODUCE","SUGAR","MANUFACTURE"};
computationArray = {6,1,2,2,1,3,3,1,3,4,4,2,1,2,1};

wordsArray包含所有不同的单词,calculateArray包含每个单词出现的次数。

我想知道是否有任何捷径可以使它看起来像这样:

var data = [{"words":"THE", "count": "6"}, 
{"words":"MAIN", "count": "1"}, {"words":"PURPOSE", "count": "2"}, 
{"words":"OF", "count": "2"}.... ];

谢谢!

2 个答案:

答案 0 :(得分:2)

您正在寻找的是d3中的zip功能:

d3.zip(wordsArray, computationArray).map(function(e) {
    return { words: e[0], count: e[1] };
});

答案 1 :(得分:1)

快捷方式称为underscore.js

npm install underscore

使用那个优秀的lib你可以做到:

var data = _.map(_.zip(wordsArray, computationArray), function(v){
   return {words: v[0], count: v[1]};
});