17
Elyz
4y

I had a response body that I needed to obtain data from. It would either come as {success: {name, id}} or {success: [{name, id},{name,id}]}
I couldn't loop over something that wasn't a list and I couldn't just ask the type of the element in success so in my infinite wisdom I split the cases by examining the length of the element in success. If it had one it was an array and could be looped over, if it didn't, it was a single object to be processed 😂 if it works it works (it's still in production, tyvm)

Comments
  • 6
    Assuming JavaScript, I'd handle it something like this:
    ```
    response => {
    const list = response.success.length ? response.success : [response.success];

    // Logic handling the list as a list, as the list is always a list now
    }
    ```
  • 6
    @Flygger see that would've been clever. Unfortunately I wasn't that clever 😂
  • 4
    Refactoring other peoples solution using hindsight can usually appear clever...

    And so can doing similar things long enough to put a decent solution on the heap of "good ways of doing those things" in the back of your head...
  • 2
    I mean that's on the people who made the API
    Either we get n elements in a list, or single object
Add Comment