本文介绍了重组JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我现在有来自服务器的JSON响应,但我想根据日期对其进行重组.例如,我现在有
I now have a JSON response from the server like, but i want to restructure it, according to dates. for e.g i now have
{
"items":
[
{
"A": [
{
"name": "a",
"date": "2/10/2010",
"sales": "100"
},
{
"name": "b",
"date": "6/10/2010",
"sales": "400"
}
],
"B": [
{
"name": "c",
"date": "2/10/2010",
"sales": "1000"
},
{
"name": "d",
"date": "6/10/2010",
"sales": "400"
}
]
},
{
"C": [
{
"name": "a",
"date": "10/10/2010",
"sales": "100"
},
{
"name": "b",
"date": "6/10/2010",
"sales": "100"
}
],
"D": [
{
"name": "c",
"date": "2/10/2010",
"sales": "300"
},
{
"name": "c",
"date": "2/10/2010",
"sales": "1100"
}
]
}
]
}
但是现在我想按日期进行重组,因为某一天需要知道所有销售情况,
but now i want to restructure by dates, for a particular day need to know all the sales to have like,
{
"date1" : [sales, sales, sales],
"date2" : [sales, sales],
"date3" : [sales]
}
这怎么办?
推荐答案
我只能假定您要这样做:
I can only assume that you want this:
var arr = JSON.parse(response); // or something like that (assuming valid JSON)
// or just assign the array literal
var result = {};
for (var i=0; i<arr.length; i++) {
var date = arr[i].date,
sales = arr[i].sales;
if (date in result)
result[date].push(sales);
else
result[date] = [sales];
}
这篇关于重组JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!