how To Iterate Through Arrays And Objects

In this tutorial, you will learn how to iterate through a collection of arrays and objects within Javascript.  In any modern day web application, taking back to some API and getting some JSON back that you have to parse is pretty much web development 101 nowadays.

Try Not To Change The Original Array

If you are new to programming, then before we go into the code to iterate through an array, one real concept you should learn is that when working with a collection within Javascript, it is a good practice to never modify the original collection you are working with.

Instead, if you need to modify or update a collection it is considered better practice to save the changes into a new array rather than of modifying the original collection. 

If you are new to programming this concept might sound strange.  A lot of coders like to write 'clean code' and creating a new collection when it's not needed can be seen as wasteful.

The reason why you should not mutate a collection (fancy word for modify) is that it significantly reduces the chances of bugs occurring.  When you create a new collection, it will also make your unit tests easier to write.  If you mutate your collection during execution, it can be really difficult to try and spot bugs.  If you want to learn a little more about this concept, I suggest you read this article for some extra information.

Arrays

Iterating through an array is the most common way you will deal with collections of data.  You can tell when you are working with an array in JSON as it will be wrapped in square brackets, like so [].  Javascript provides numerous ways to iterate through an array, functions like map(), reduce(), filter() and forEach() can all be used.

    myArray.forEach((data) => {
      const property = data.property;
    });

Objects

Sometimes you may need to deal with a collection of objects, like so:

        "locale": {
            "en": {
                "name": "england",
            },
            "fr": {
                "name": "france",
            }
        }

 

When dealing with an object, you cannot use the array methods. Instead, you need to use object.keys to get the name of each objection in the collection. After you have all the 'keys' within the collection, you can then do a forEach using, the key to get the data you need like so:

Object.keys(locale).forEach(key => {
     const name = locale[key].name;
});

submit to reddit

Jon D Jones

Software Architect, Programmer and Technologist Jon Jones is founder and CEO of London-based tech firm Digital Prompt. He has been working in the field for nearly a decade, specializing in new technologies and technical solution research in the web business. A passionate blogger by heart , speaker & consultant from England.. always on the hunt for the next challenge

Back to top