Create two dimensional array JSON JavaScript
In this demo you will see how to create two dimensional array JSON object in JavaScript by iterating List<Map<String, Object>> JSON object return back from server side as structure give below:
[ { "ric": "ADAG.DE", "sedol": "5653487", "quantity": 107479, "activityQuantity": null, "businessDate": 20141023 }, { "ric": "ADAG.DE", "sedol": "BBJPFY1", "quantity": 2758, "activityQuantity": null, "businessDate": 20141023 }, { "ric": "ADAG.DE", "sedol": "5653487", "quantity": 107479, "activityQuantity": null, "businessDate": 20141023 }, { "ric": "BDAG.DE", "sedol": "5653487", "quantity": 107479, "activityQuantity": null, "businessDate": 20141023 }, { "ric": "BDAG.DE", "sedol": "5653487", "quantity": 107479, "activityQuantity": null, "businessDate": 20141023 } ]
- Finally using JavaScript we will convert above JSON object in below key and two dimensional array where we will put businessDate and quantity as values in two dimentional array JSON object as below:
[ { "key": "ADAG.DE", "values": [ [ 20141023, 107479 ], [ 20141023, 2758 ], [ 20141023, 107479 ] ] }, { "key": "BDAG.DE", "values": [ [ 20141023, 107479 ], [ 20141023, 107479 ] ] } ]
- jsontest.html page with logic:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Create two dimensional array JSON JavaScript</title> <script> function buildJSONData(){ var data = [ { "ric": "ADAG.DE", "sedol": "5653487", "quantity": 107479, "activityQuantity": null, "businessDate": 20141023 }, { "ric": "ADAG.DE", "sedol": "BBJPFY1", "quantity": 2758, "activityQuantity": null, "businessDate": 20141023 }, { "ric": "ADAG.DE", "sedol": "5653487", "quantity": 107479, "activityQuantity": null, "businessDate": 20141023 }, { "ric": "BDAG.DE", "sedol": "5653487", "quantity": 107479, "activityQuantity": null, "businessDate": 20141023 }, { "ric": "BDAG.DE", "sedol": "5653487", "quantity": 107479, "activityQuantity": null, "businessDate": 20141023 } ]; var tempmap = {}; var jsonData = []; for ( var j = 0; j < data.length; j ++ ) { if (!(data[j].ric in tempmap)) { jsonData.push ( { key: data[j].ric, values: [] } ); tempmap[data[j].ric] = jsonData.length - 1; } jsonData[tempmap[data[j].ric]].values.push ([data[j].businessDate,data[j].quantity]); } document.write(JSON.stringify(jsonData)); } </script> </head> <body> <input type="button" value="Build JSON data onclick" onclick="buildJSONData();"> </body> </html>
Output:
Click button Build JSON data onclick you will see below output:
Run in Plunker here