UndescoreJS - 将对象属性转换为数组

时间:2016-04-25 20:01:32

标签: javascript angularjs underscore.js chart.js

案例很简单 - 我有一个对象列表:

[
{"id":"0001","status":"prod"},  
{"id":"0002","status":"prod"},  
{"id":"0003","status":"prod"},  
{"id":"0004","status":"prod"},  
{"id":"0005","status":"dev"},  
{"id":"0006","status":"dev"}
]

当我使用_.groupBy('status')时,结果为:

{
    prod: [{"id":"0001","status":"prod"},  
        {"id":"0002","status":"prod"},  
        {"id":"0003","status":"prod"},  
        {"id":"0004","status":"prod"}],
    dev: [{"id":"0005","status":"dev"},  
        {"id":"0006","status":"dev"}]
}

但我需要像下面的代码一样的结果发送到Chart.js(使用Underscorejs):

{
    legend: ['prod','dev'],
    data: [4,2]  // Array Length  
}

如何使用Underscore.js解决我的问题?

3 个答案:

答案 0 :(得分:3)

在一个链中,只是为了好玩。

_.chain(data)
  .groupBy('status')
  .mapObject(x => x.length)
  .pairs()
  .unzip()
  .zip(['legend', 'data'])
  .map(x => x.reverse())
  .object()
  .value();

答案 1 :(得分:0)

只需要再做一步:

 var output = {
     legend: [],
     data: []
 }
 _.chain(rawData).groupBy('status').each(function(value,key){
       output.legend.push(key);
       output.legend.push(data.length);
 })

答案 2 :(得分:0)

var legend = _.uniq(_.pluck(data, 'status'));
var groupedData = _.groupBy(data, 'status');

var result = {
    legend: legend,
    data: _.map(legend, function(status) {
        return groupedData[status].length;
    })
};