重新排序JSON集合 [英] Reorder a JSON collection
问题描述
我的服务器中有一个JSON数组提取,如下所示:
I have a JSON array fetch from my server which looks like :
[ {name: "Web Design", id: "27", month_n: "1", data: "68.00"},
{name: "Web Design", id: "27", month_n: "2", data: "56.00"} ,
{name: "Homework", id: "4", month_n: "2", data: "15.00"} ,
{name: "Gaming", id: "12", month_n: "2", data: "5.00"} ]
在客户端,我想重新排序类似于:
On the client side, I want to reorder this to have something similar to :
[{name: "Web Design", data:[68.00,56.00]}, {name:"Homework", data:[0,15]} and so on...
数据 值按id编号和月份编号分组(如果没有匹配的月份,则默认为0)。
Where the "data" value is grouped by the "id" number and the month number (by default 0 if there's no month that match).
最好的方法是什么?我尝试了纯粹的JavaScript方式,但是我很难过!我也听说过使用下划线JS更容易。但不知道从哪里开始。
What's the best way ? I tried it the pure JavaScript way but I'm getting a hard time ! I have also heard It is easier with underscore JS. But don't know where to start.
有人请赐教吗?
推荐答案
这可以做到通过两个操作:
This can be done by two operations:
- Groupby [ name ]字段,然后
- 插入[数据]字段
- Groupby [name] field, then
- Pluck [data] fields
有一些纯JS数组原型扩展库可以实现这一点和许多其他几行的操作。你可以看一下underscore.js。我还编写了一个简单的JS库 jsList 。它附带了许多单元测试作为示例。
There are pure JS array prototype extensions libraries to achieve this and many other operations with couple of lines. You may take a look at underscore.js. I have also written a simple JS library jsList. It comes with many unit-tests to use as example.
你只需要写这些行:
var arr = [ {name: "Web Design", id: "27", month_n: "1", data: "68.00"},
{name: "Web Design", id: "27", month_n: "2", data: "56.00"} ,
{name: "Homework", id: "4", month_n: "2", data: "15.00"} ,
{name: "Gaming", id: "12", month_n: "2", data: "5.00"} ];
var temp = arr.groupBy(function(item){ return item.name });
var result = [];
for(var key in temp){
result.push({name: key, data: temp[key].pluck('data')});
}
您可以使用Object.keys来避免for循环,但它只会来使用Javascript 1.8.5或更高版本。
You may use Object.keys to avoid the for loop, but it only comes with Javascript 1.8.5 or later.
谢谢。
这篇关于重新排序JSON集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!