Use this trick to map over single objects in Javascript
Arika O
Posted on April 29, 2020
The title is of course, misleading. We know from Javascript that we can't use the .map()
method on non-arrays so what I am talking about? Let's say we make a request to a server and then we convert the json text into the corresponding object. It is of course possible that after the parsing we get back a single object and not an array. If we'll try to iterate over the result, .map()
won't work so we'll run into issues. You can see this happening in the code bellow. For simplicity, I didn't fetch any real data, I used some hard-coded one. We have a simple React component that should display the names of the imaginary people we get back from the server. When trying to run the code we'll get an error: Property 'map' does not exist on type Object
.
How can we avoid this situation and make sure that we'll be able to map over the result, even if we get a single object after parsing the response? Let's look at the code bellow:
What we did was use the Array.isArray()
built-in method to check if what we get back is an array and if it's not, we store the single object into a single element array. Since .map()
iterates over single entry arrays, we won't run into an error. You can see the complete code here: https://codesandbox.io/s/sass-jzgxv
P.S: this excludes, of course, the scenario in which fetch returns nothing so then we'll have to check for null responses.
Image source: @divinetechygirl on Pexels
Posted on April 29, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
January 26, 2023