Question: I have a javascript application, that calls an api, and the api returns json. With the json, I select a specific object, and loop through that.

My code flow is something like this:
Service call -> GetResults
Loop through Results and build Page

The problem though, is sometimes that api returns only one result, so that means it returns an object instead of an array, so I cant loop through results. What would be the best way to go around this?

Should i convert my object, or single result to an arrary? Put/Push it inside an array? or should I do a typeof and check if the element is an array, then do the looping?

Thanks for the help.

```
//this is what is return when there are more than one results
var results = {
pages:  [
        {"pageNumber":204},
        {"pageNumber":1024},
        {"pageNumber":3012}
    ]
}

//this is what is returned when there is only one result
var results = {
    pages: {"pageNumber": 105}
}

```

My code loops through results, just using a for loop, but it will create errors, since sometimes results is not an array. So again, do I check if its an array? Push results into a new array? What would be better. Thanks

Answer: 
If you have no control over the server side, you could do a simple check to make sure it's an array:

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

// Do your loop here.

```

Otherwise, this should ideally happen on the server; it should be part of the contract that the results can always be accessed in a similar fashion.
Arrange whatever you do to your objects inside the loop into a separate procedure and if you discover that the object is not an array, apply the procedure to it directly, otherwise, apply it multiple times to each element of that object:

```
function processPage(page) { /* do something to your page */ }

if (pages instanceof Array) pages.forEach(processPage);
else processPage(pages);

```

Obvious benefits of this approach as compared to the one, where you create a redundant array is that, well, you don't create a redundant array and you don't modify the data that you received. While at this stage it may not be important that the data is intact, in general it might cause you more troubles, when running integration and regression tests.