Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Rearranging a Json object

Status
Not open for further replies.

jsonguy

Programmer
Jun 16, 2014
2
GB
I am trying to convert a json object that contains:

Code:
var dataold = [{
    "DateGroup": "05/15/2012",
    "Product": "Var1",
    "Duration": 0
  },{
    "DateGroup": "05/15/2012",
    "Product": "Var2",
    "Duration": 53.999700
  },{
    "DateGroup": "05/15/2012",
    "Product": "Var3",
    "Duration": 86.999580
  }
];

to this format:


Code:
var datanew = [{
    "DateGroup": "05/15/2012",
    "var1": 0,
    "var2": 53.999700,
    "var3": 86.999580
  },{
    "DateGroup": "06/17/2012",
    "var1": 32.999880,
    "var2": 59.999700,
    "var2": 59.999700
  },{
    "DateGroup": "07/19/2012",
    "var1": 37.999880,
    "var2": 0,
    "var3": 83.999580
  }
];

but am not sure how to go about parsing the object and making the necessary changes.
 
it will probably be easier to do this in whatever server side software you use to generate the input. If you must do it in javascript then you will need to constuct some nested loops or tweak your structure a little bit (in which case you can probably get it done in a single loop).
 
I need to do it in Javascript. I've been trying to do it with nested loops, but without much success.
 
i have not tested it but something like this might work. it's not exactly the same output format, but close.

Code:
<!DOCTYPE html>
<html>
<body>

<p id="demo"></p>

<script>
var nO = {};
var oO = [{
    DateGroup: "05/15/2012",
    Product: "Var1",
    Duration: 0
  },{
    DateGroup: "05/15/2012",
    Product: "Var2",
    Duration: 53.999700
  },{
    DateGroup: "05/15/2012",
    Product: "Var3",
    Duration: 86.999580
  }
]; 
for(var i = 0; i < oO.length; i++){ 
for(var i = 0; i < oldO.length; i++){ 
 if(!(oldO[i].DateGroup in nO))nO[oldO[i].DateGroup] = {};
 nO[oldO[i].DateGroup][oldO[i].Product] = oldO[i].Duration;
}
document.getElementById('demo').innerHTML = JSON.stringify(nO);
</script>
</body>
</html>


 
and just in case you don't know how to retrieve the data

Code:
for(var dateGroup in nO){
 for(var Property in nO[DateGroup]){
   var Duration = nO[DateGroup][Property];
   // you now have the dategroup, the property and the duration for that property
 }
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top