Create two dimensional array JSON JavaScript selected Key
Here you will see how to create two dimensional array JSON JavaScript selected “ric”: “ADAG.DE” where data is in the form of List<Map<String, Object>> JSON object and one particular key has been selected by the user and based on that we will have to create modified JSON object:
- Supplied JSON object:
[ { "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 } ]
- Out put JSON object is based on the user selection of the “ric”: “ADAG.DE” where we will create key as selected ric and value will be two dimensional array of businessDate and quantity as below:
[ { "key": "ADAG.DE", "values": [ [ 20141023, 107479 ], [ 20141023, 2758 ], [ 20141023, 107479 ] ] } ]
HTML code:
<!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 selected Key</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 = []; var selectedRic = "ADAG.DE"; for ( var j = 0; j < data.length; j ++ ) { if (data[j].ric == selectedRic) { 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:
Run above code in Plunker here