My FeedDiscussionsHeadless CMS
New
Sign in
Log inSign up
Learn more about Hashnode Headless CMSHashnode Headless CMS
Collaborate seamlessly with Hashnode Headless CMS for Enterprise.
Upgrade ✨Learn more
Using JavaScript Map method on a subarray inside an array of Objects

Using JavaScript Map method on a subarray inside an array of Objects

Oghenetega Philip's photo
Oghenetega Philip
·Jan 5, 2022·

2 min read

Late into the year 2021, I was practicing my frontend skills with a task from frontend mentors. I was given a folder to get started with, inside the folder was a data.json file and other assets I would need. The data.json preview is shown below

carbon.png

Going through the data content, you can see it's an array of objects with an array nested inside it. I spent a good twenty minutes wondering how to return the contents of the comment array. I actually search through google trying to find a quick solution to it and I actually didn't see what I like which is what prompted me writing this article.

I realized I was doing the wrong thing by using just one map method. In other to make this work, you would need to use two map methods. The first map runs on the outermost and the second map for the inner array.

image.png

The map() method takes a callback method that performs an operation on the elements in the array. It returns a new array containing the resulting values of running the operation on each element with the parameter it accepts.

In this example, I pass the callback function the data parameter and we use that parameter to get to the comment object which contains the array we are looking for.

Since the comment object is an array as well, we can run the map function on it too, like below.

image.png

The result of the expression above will be another array. We pass this array to the constant called showComments.

image.png

Displaying the result in the console would be

image.png

There you have it, you have successfully mapped an array inside an array of object.

That's for my first blog post guys. I hope that you have learned something new from this blog post. If there is a better way of doing it, please comment below. Meet y'all in the next blog post goodbye for now 👋.