September 16, 2019

Working with Javascript Array of Objects

A young boy wearing a white VR headset

Image credit to Any IP Ltd
anyip.io

Array of objects is a common data structure that you will find frequently when you are working with a list in a modern Javascript framework. As a list, you will easily loop it by for Each () method or for the () function to access each of the Array’s elements in order to manipulate it.

But Javascript now has some Array’s methods that will help you to manipulate the elements and makes your life as a JS engineer much easier. The strength of these methods is that it doesn’t change the original data so you can safely manipulate the values without worrying about the original one. We wanted to share a few of them that our creative technology development team have regularly been using in some recent in projects.

Array.map()

Array map () will create a new array that a result from manipulating the original array. This method is powerful as in my imagination it’s working as for Each () in simpler and more compact syntax.

This is an example:

sample javascript array map

If you need a new array that only contains email address only from the data, you can map () the array:

sample javascript people email

The map () method is handy too if you think you need to manipulate the data a bit (adding new property) before further process. Let say you need 1 new property “location” that indicates all “Senior Developer” are from “Bali” and others are from “Sydney”. You can write your map () something like this:

sample javascript new people

Array.find()

find () method will return the first element that is found in the Array. This method, as the name says it, is helpful for us to find the element, based on the criteria you have set, in the Array.

sample javascript find method

Array.filter()

filter() will return a new array, based on the search criteria that is set. So it can be an empty or filled array.

sample javascript filter people

Putting Them All Together

This section will show you how we use the sample above in a vue.js project. I have 1 page, About Us page, that shows the list of personnel with a filter search form. The search/filter in this example is only found in the “name” field only.

The page will look like this:

sample page using javascript array of objects