Working with Javascript Array of Objects

Javascript Code on Screen

Array of objects is a common data structure that you will find frequently when you are working with a list in 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 element 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:

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

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:

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.

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.

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 personnels 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:

Share this:

0 Comments

Leave your comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.