我有一个API调用返回的以下JSON对象
Object {Result: Array[5]}
Result: Array[5]
0: Object
id: 1
name: "Mark"
joinDate: 2014-05-03T22:12:05.000Z
balance: 2201
1: Object
2: Object
3: Object
4: Object
5: Object
length: 5
__proto__: Array[0]
__proto__: Object
我需要在此处对数据进行分组,并在每个月的每一天生成一个新的对象分组客户端数量及其余额。所以我最终得到一个对象(假设我根据上面的对象为May生成一个对象):
{
0:Object
id: 1 >> Referring to Day 1 of the month
nof_of_clients: 5
total_balance: 30,899
1:Object
id: 2 >> Referring to Day 2 of the month
nof_of_clients: 12
total_balance: 20000
2:Object
id: 5 >> Referring to Day 5 of the month
nof_of_clients: 2
total_balance: 1200
}
所以我想知道是否有可能通过Javascript做到这一点,如果是的话,怎么样?任何例子都将受到高度赞赏。感谢
答案 0 :(得分:1)
好吧,你需要遍历你的结果并生成一个对象,根据需要对数据进行分组。首先,您需要计算每个结果的日,月和年:
for(var i=0;i<result.length;i++){
result[i].day=result[i].joinDate.split('T')[0];
var arr=result[i].day.split('-');
result[i].day_of_month=Number(arr[2]);
result[i].month=Number(arr[1]);
result[i].year=Number(arr[0]);
}
然后你需要遍历结果并生成一个按年,月,日分组的对象:
var arr={};
for(var i=0;i<result.length;i++){
current=result[i];
if(!arr.hasOwnProperty(current.year)){//if year doesnt exist, create year
arr[current.year]={};
}
if(!arr[current.year].hasOwnProperty(current.month)){// if month doesnt exist, create month
arr[current.year][current.month]={};
}
if(!arr[current.year][current.month].hasOwnProperty(current.day)){//if day doesnt exist, create day
arr[current.year][current.month][current.day]={
id:current.day_of_month,
nof_of_clients:1,
total_balance:current.balance
}
}else{//if day already exists, add 1 to the number of client and add the balance to total balance
arr[current.year][current.month][current.day].nof_of_clients+=1;
arr[current.year][current.month][current.day].total_balance+=current.balance;
}
}
这是一个完整的小提琴:http://jsfiddle.net/juvian/3auBG/1/
答案 1 :(得分:1)
首先通过Result
循环,然后使用joinDate
方法从Date
字符串创建日期对象,然后按年/月/将项目分组到新对象groupedResult
日订单:
var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var groupedResult = [];
for (var i = 0; i < Result.length; i++)
{
var date = new Date(Result[i].joinDate), day = date.getDate(), month = months[date.getMonth()], year = date.getFullYear(), d = "day " + day;
if (!groupedResult.hasOwnProperty(year)) groupedResult[year] = {};
if (!groupedResult[year].hasOwnProperty(month)) groupedResult[year][month] = {};
if (groupedResult[year][month].hasOwnProperty(d))
{
groupedResult[year][month][d].no_of_clients += 1;
groupedResult[year][month][d].balance += Result[i].balance;
}
else groupedResult[year][month][d] = {"id": day, "no_of_clients": 1, "balance": Result[i].balance};
}
答案 2 :(得分:0)
以下是一个示例:http://jsfiddle.net/Pnax8/1
RegExp("^([0-9]{1,4})-([0-9]{1,2})-([0-9]{1,2})T([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})(.([0-9]+))?Z$")
答案 3 :(得分:0)
这是理想: