
A loop in computing is an instruction that iterates or repeats or executes one or more statements over and over again.
Some loops execute the statement so long as the specified condition is true, while others execute the statement up to a number of times.
I'm sure there's a loop functionality in your music player, where you can select a particular song to be repeated over and over again. This means that a loop basicallyrepeats something!
Today, I will talk about how to loop through an Object. But before we continue, I would like you to understand what Objects are and how you could create one.
REFRESHER
What is an Object?
An Object is a special kind of array that stores data as a {key-value} pair. A single pair of this data is called a property of that object.
Below are some of the ways to create an object in JavaScript;
Object Literal
Using theobject literal {}
, we can create a simple object that stores a user's name and email address.
constprofile={name:"Simon",email:"me@you.com"}//retrieve the user's nameconsole.log(`${"Hello",+profile.name}`);
Constructor Function
A constructor function is a function that is used to create an object.
You just have to declare the function, then make use ofthis
keyword within the function to set the function's properties.
functionprofile(name,email){this.name=name;this.email=email;}//create new instanceconstmyProfile=newprofile("simon","test@gmail.com");//retrieve user emailconsole.log(`${"My email is"+myProfile.email}`);
You can see how I declared the function, then made use of this keyword to define properties that the function will have.
To create an object using a constructor function, you have to create a new instance of that function using anew
keyword.
Factory Function
A factory function is a function thatreturns an object. To create a factory function, you must first declare a function, then on your return statement, use theObject literal notation to return the object.
functionprofile(name,email){return{name:name,email:email}};//invoke functionconstmyProfile=profile("Tony","test@gmail.com");//access propertyconsole.log("My name is"+myProfile.name);
Having refreshed your memory, I will show you different approaches to looping through an Object.
Before we proceed with any of the approaches, I would like you to understand these two Object methods.
Object.keys()
This method helps to retrieve all keys belonging to an Object as anArray
Object.values()
This method helps to retrieve all values belonging to an Object as anArray
With a knowledge of the object methods above, we can write a loop that will loop through an object.
APPROACH 1 ( Using a number as the Index )
Now, remember that an Object property is just a combination of a key and a value
ie{ key : value }
. So using theObject.keys()
method, we can retrieve all keys belonging to an Object, loop through the keys using awhile-loop<
, and then with a particular key as a numeric index, we will retrieve the value that is assigned to it.
constprofile={name:"Simon",email:"me@you.com",gender:"male"}leti=0;//get the length of the objectwhile(i<Object.keys(profile).length){//since we hold the current index, retrieve the key and value assigned to itconsole.log(Object.keys(profile)[i]+' ='+Object.values(profile)[i]);i++;}
In the code above, the object has3 properties and in order to loop through the object's keys, we have to:
- Query the length of the keys
- Access all object keys and check the key that is present at the specified
index
. - Access all object values and check the value that is present at the specified
index
.
APPROACH 2 ( Using a key as the Index )
Recall that usingObject.keys() method retrieves the object's keys as an
Array
.
In this approach, we will use afor-each
loop to loop through the object's keys which are returned as anArray, then with a particular key as the element at hand, we can access the value assigned to it.
constprofile={name:"Simon",email:"me@you.com",gender:"male"}//loop through keysObject.keys(profile).forEach((key)=>{//access object value using keyconsole.log(key+' ='+profile[key]);});
APPROACH 3 ( Using for..in loop )
Considering the second approach above, we can achieve the same results by using thefor ...in loop
.
In this approach, we need to define the loop's syntax to access each key present in the object. Then with each key accessed, retrieve the associated value.
for(letkeyinprofile){console.log(key+' ='+profile[key]);}
This approach is by far the easiest way to loop through an Object.
I hope you've understood the 3 approaches you could use to loop through an Object in JavaScript.
You've reached the end of my article.
EXTRA
I recently launched a JavaScript package that validates your HTML forms using validation rules, regular expressions, and form input attributes.
I will appreciate it if you spared a few seconds to check it out.
Thank You
Image Credit: Tine Ivanič on Unsplash
Top comments(0)
For further actions, you may consider blocking this person and/orreporting abuse