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

UndescoreJS - Convert Object Properties Into Arrays

本文关键字:转换 数组 属性 对象 undescoreJS      更新时间:2023-09-26

情况很简单 - 我有一个对象列表:

[
{"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  
}

如何使用下划线.js来解决我的问题?

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

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

只需要再走一步:

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