Tuesday, 23 August 2016

How to loop around a JSON result...

Okay, I spent ages looking for how to do this. The tricky part I found was marrying up the data in the response from the server, and the labels that people were giving different parts of the request... Soooooo I'm going to add to the noise, and hopefully help a few people out.

First up - the address of my service that's providing the JSON data:

/sap/opu/odata/sap/ZPD_RR_SRV/RepairActivitySet

Although clearly, that's the oData, so with the JSON tag on the end:

/sap/opu/odata/sap/ZPD_RR_SRV/RepairActivitySet?$format=json

This returns a list of Repair Activities (viewed from Gateway):




Note that it has the structure d/results/{Rakey/Radesc}

This is what I wanted to loop around in my UI5 javascript application, in one of my ViewControllers.

Here's the complete code that reads the lot: 

var NRAModel = new sap.ui.model.json.JSONModel();
NRAModel.loadData("/sap/opu/odata/sap/ZPD_RR_SRV/RepairActivitySet", null, false); 
var NRAModelArray = NRAModel.getData();


var myResults = [];

myResults = NRAModelArray.d.results;
console.log(myResults.length);

for( i = 0; i < myResults.length; i++) {
     var obj = myResults[i];
      console.log(myResults[i]);
      console.log(myResults[i].Rakey );
      console.log(myResults[i].Radesc);

}


The thing to note here, is that myResults is declared as an Array, and is populated by passing the d.results content from the original NRAModel.getData

d.results, you'll notice, is the same path as that provided by my Service, in the first screenshot.

Using console.log as you go along really helps with understanding what each of the variables are doing.





1 comment:

  1. If i can hug you, i would, as i am looking for this one for 3 days now.

    ReplyDelete