Restructure 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': [
Solution 1:
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 literalvar 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];
}
Solution 2:
Assuming you get your JSON worked out:
<?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);
?><scriptsrc="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script><script>varJSON = '<?phpecho 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>
I added the php section to show what a JSON string should look like. This solution also requires jQuery.
Post a Comment for "Restructure Json"