I have a JavaScript application that makes an API call and receives JSON data in return. From this JSON data, I need to select a specific object and iterate through it.
The flow of my code is as follows: Service call -> GetResults Loop through Results and construct Page
The issue arises when the API returns only one result, resulting in an object instead of an array. This prevents me from looping through the results. How should I handle this situation?
Should I convert the object or single result into an array? Place/Push it inside an array? Or should I use typeof to determine if the element is an array before looping through it?
Thank you for your assistance.
//JSON data returned when there are multiple results
var results = {
pages: [
{"pageNumber": 204},
{"pageNumber": 1024},
{"pageNumber": 3012}
]
}
//JSON data returned when there is only one result
var results = {
pages: {"pageNumber": 105}
}
My code currently loops through the results using a for loop, but it encounters errors when results is not an array. Should I check if it's an array before proceeding? Should I push the results into a new array? What would be the best approach? Thank you