undescoreJS - 将对象属性转换为数组
UndescoreJS - Convert Object Properties Into Arrays
情况很简单 - 我有一个对象列表:
[
{"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;
})
};
相关文章:
- Javascript转换数组
- JSON.stringify不转换数组
- 使用underscore.js转换数组
- 对象转换数组
- 在 JavaScript 中的值列表中转换数组
- 转换数组并反转
- 用一个巨大的字符串“”转换数组;数字”;,用逗号分隔成一个数字数组(而不是字符串)
- 用javascript转换数组中的日期
- 如何转换数组字符串
- 转换数组中的输入值
- 如何在创建数组后转换数组中的var
- Json转换数组是一个字符串
- 在AngularJS中转换数组属性
- 在javascript中转换数组
- 动态转换数组为树状结构
- 使用Javascript和Underscore.js转换数组对象
- node.js中使用node-gyp的转换数组
- Nodejs -转换数组
- D3 js转换数组的矩形不工作
- 在Javascript中转换数组的数字到字符串