Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

json object vs array of objects

I'm querying a remote server and receiving a json reponse. The format of the reponse depends on the number of objects in the response. If there is a single object it looks similar to:

"results": {
  "meeting": {
    "location": "Location A",
    "time": "1378033200"
  }
}

But if there is more then one object in the response, I get an array of objects instead:

"results": {
  "meeting": [
    {
      "location": "Location A",
      "time": "1378033200"
    },
    {
      "location": "Location B",
      "time": "1379250000"
    }
  ]
}

The complete response from the server includes a "count" variable, so I can distinguish between the two situations. In my Javascript at the moment I first check the count, and if there is exactly one object, I read out the location and time information similar to:

var location = results.meeting.location;
var time = results.meeting.time;

If there is anything other than exactly one object, I do

for(var i=0; i<count; i++) {
  var location = results.meeting[i].location;
  var time = results.meeting[i].time;
}

This works, but I'm wondering if there is a more elegant way of handling the two situations?

like image 835
Tom Avatar asked Dec 30 '25 18:12

Tom


1 Answers

Always you can loop it as an array,

if(!(results.meeting instanceof Array)){
   results.meeting = [results.meeting];
} 

So you will get always an array , if one an array with one data

So and after always

var count = results.meeting.length;
for(var i=0; i<count; i++) {
  var location = results.meeting[i].location;
  var time = results.meeting[i].time;
}
like image 163
Sarath Avatar answered Jan 02 '26 08:01

Sarath



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!