我现在有来自服务器的JSON响应,但我希望根据日期对其进行重组。因为我现在有
{
"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"
}
]
}
]
}
但现在我想按日期进行重组,因为某一天需要了解所有销售情况,
{
"date1" : [sales, sales, sales],
"date2" : [sales, sales],
"date3" : [sales]
}
怎么办呢?
答案 0 :(得分:4)
我只能假设你想要这个:
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];
}
答案 1 :(得分:0)
假设你得到了你的JSON:
<?php
$list = array(
array(
'product' => 'a',
'date' => '2012-08-01',
'sales' => 500,
),
array(
'product' => 'b',
'date' => '2012-08-02',
'sales' => 600,
),
array(
'product' => 'c',
'date' => '2012-08-01',
'sales' => 250,
),
array(
'product' => 'd',
'date' => '2012-08-02',
'sales' => 800,
),
);
echo json_encode($list);
?>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
var JSON = '<?php echo json_encode($list); ?>';
var pJson = jQuery.parseJSON(JSON);
var cArray = new Array();
for each ( i in pJson ) {
if ( typeof cArray[i.date] == 'undefined' ) {
cArray[i.date] = Array();
}
cArray[i.date].push(i.sales);
}
</script>
我添加了php部分来显示JSON字符串应该是什么样子。这个解决方案也需要jQuery。