Log In

Looping through Objects’s Keys and Values in JavaScript

Looping through Objects’s Keys and Values in JavaScript
13.03.2024
Reading time: 9 min
Hostman Team
Technical writer

JavaScript, a user-friendly programming language with important components such as object keys and values, serves as a robust creator of dynamic and interactive web applications. Complex and constantly changing data require efficient iterating over the object's keys and values. It is precisely the 'iterating through object keys and values' concept, or simply JS looping through object keys and values that provides access and performs required actions.

Once you master these techniques, you can skillfully manipulate data and enhance the functionality of your applications. A foundational skill for any JavaScript developer improves the manipulation and processing of complex data sets, making your code more dynamic and flexible. While constantly changing and updating data, developers can easily access and manipulate data using this cost-effective method without repeating code.

In this article, we’ll delve into various techniques and methods to loop through object keys and values in JS, so you’ll learn how to apply them in your code. Whether you are a beginner or an experienced developer, read on to discover how to improve your data manipulation skills and efficiently apply them in your own projects. Explore the world of looping through object keys and values in JavaScript.

Objects in JavaScript

Before diving into the theory and practice, let's start with understanding what objects are in JavaScript. So, they are a collection of key-value pairs, where the key is a unique identifier and the corresponding value is any data type. They allow data to be stored and manipulated in a structured and organized way. Also they contain any number of key-value pairs with different data types.

The loop through object feature in JS stands for creating complex objects, suitable for storing, sorting, filtering, searching and manipulating large amounts of data. Objects can have functions as their values, known as methods, which perform specific actions or operations on the object's data. New key-value pairs can be added to an object, existing values can be modified, or even deleted if required.

Basic for loop through object keys and values in JS

The JS for loop is commonly used for iterating through arrays and objects as well as for looping through object keys and values, especially to get access and manipulate specific properties within an object. 

To start, learn the basic for loop method for looping through an array:

for (var i = 0; i < array.length; i++) {
// code to be executed
}

This for loop has three parts:

  • the initialization (var i = 0)

  • the condition (i < array.length)

  • the increment (i++).

The loop runs as long as the condition is true, and each time it loops, the i value is increased. This feature gives access to each element in the array with the help of the i index.

To use a similar for loop to iterate through object keys and values, you should apply the for...in loop designed specifically for objects:

for (var key in object) {
// code to be executed
}

In this loop, the variable key takes on the value of each key in the object as it loops through the JS object. This feature gives access to the corresponding value for each key via object[key].

For instance, for an object called site with the properties web name, age, and occupation, each property and its value can be accessed via the for...in loop:

var site = {
web name: 'Hostman',
age: 5,
occupation: 'cloud service provider'
};

for (var key in site) {
console.log(key + ': ' + site[key]);
}

// Output:
// name: Hostman
// age: 5
// occupation: cloud service provider

So, the for...in loop gives an easy access to all the keys and values in an object without having to know the exact names of the properties in advance. This is useful for interacting with large and complex objects.

The for...in loop is also used to check if a specific property exists in an object, and modify its value by using the hasOwnProperty() method:

for (var key in site) {
if (site.hasOwnProperty(key)) {
// code to be executed
}
}

The for loop feature for iterating through object keys and values in JS provides quick access to the properties and the ability to manipulate them within an object. By understanding the syntax and usage of the feature, you can improve the functionality of working with objects and shorten your code.

The Object.keys() method to loop through objects in JS

The built-in Object.keys() method in JavaScript allows you to get an array of all the keys of a given object. The JS feature is designed to loop over all the properties of an object because it is a simple way to access and manipulate each key individually. The idea is to pass the object you want to get the keys from as a parameter, and the method returns an array of all the keys in that object.

Static method syntax is called directly on the Object class, not on the object instance. That's why it got its name Object.keys(). The parentheses after the method name are used to pass the object from which you want to get the keys.

For instance, for an object called site with properties such as web name, age, and occupation, apply the following Object.keys() method:

Object.keys(site)

The JS method will loop over the properties of the passed object and return an array of all keys. The keys in the array are arranged in the same order in which they appear in the object due to the fact that objects in JavaScript are unordered, meaning there is no guarantee that the properties will be returned in a particular order. However, the Object.keys() method ensures that the keys are returned in the order in which they were added to the object.

The Object.values() method to loop through objects in JS

The Object.values() method allows you to quickly access and retrieve all the values ​​of an object as an array, simplifying the way you manipulate and loop through an array of objects in JS. For instance, for an object called site that contains various properties such as web name, age, occupation, using the Object.values() method allows retrieving all the values of this object in the form of an array.

The syntax is simple and consists of passing the object site as a parameter:

const siteValues = Object.values(site);

This feature will return an array with all the site object values in the same order as they are defined in the object. This array helps performing various operations, such as filtering or sorting the data.

Combining Object.keys() and Object.values() for efficient object iteration in JavaScript

The Object.keys() and Object.values() methods provide a more efficient way of how to loop through an object in JS. The first one returns an array of all the keys present in an object, while the second one returns an array of all the corresponding values. The combination of both methods gives access to both the keys and values ​​of an object.

For instance, for an object called site with properties like web name, age, occupation, apply the following code.

const site = {
web name: 'Hostman',
age: 5,
occupation: 'cloud service provider'
};

const keys = Object.keys(site);
const values = Object.values(site);

console.log(keys); // Output: ['web name', 'age', 'occupation']
console.log(values); // Output: ['Hostman', 5, 'cloud service provider']

As a result of the synergy of both methods, two arrays were returned containing the keys and values of the site object. They are easily accessed and manipulated to perform any operation on the object, including loop through object properties in JS.

The for...of method to loop through object in JS

The for...of loop provides a simplified syntax compared to the traditional for...in loop, iterating over the values of an object while working with arrays, strings, and other iterable objects. The feature eliminates errors or bugs in code as there is no need for manual counting or using a counter variable. Automatically iterating over each element of the iterable object and assigning it to a variable improves the loop through object keys in JS.

The feature can be used with any iterable object, regardless of its length or size, with a variable number of elements, such as arrays. For instance, if you want to print out each flower separately, use the for...of loop. 

To start, declare the array of flowers:

const flowers = ['rose', 'daisy', 'violet'];

Next, apply the for...of loop to iterate over the elements in the flowers array and print out each flower:

for (const flower of flowers) {
console.log(flower);
}

In this code, the variable flower is automatically assigned to each element in the flowers array in every iteration of the loop, allowing the value of each flower to be accessed and printed without manually declaring and incrementing a counter variable.

The Object.entries() method in JavaScript

The Object.entries() method stands for efficient iteration through the keys and values of an object. Simple access to and manipulation of object properties eliminates the need for complex syntax or methods. It takes an object as a parameter and returns an array of arrays. Each inner array consists of two elements, where the first is the object's property key, and the second is the corresponding value. This is a useful feature to loop through an object and access both the keys and values at the same time in JS.

For instance, for an object called site with properties such as web name, age, and occupation, apply the Object.entries() method to loop through this object and access both the keys and values.

The syntax looks as follows:

Object.entries(site);

This will return an array of arrays with the following structure:

[['web name', 'Hostman'], ['age', 5], ['occupation', 'cloud service provider']]

Each inner array contains two elements, the key and value of the object property to access both of them in a single iteration. This method can be used in conjunction with a for loop to iterate through the array and perform any desired operations with the objects in JS. It also allows us to convert an object into an array of key-value pairs to manipulate or transform an object into a different data structure.

For instance, apply the Object.entries() method to convert an object into a Map, which is a data structure with key-value pairs.

To do this, use the following syntax:

const map = new Map(Object.entries(site));

This will create a new Map with the same key-value pairs as the original object.

Conclusion

Loop through object keys and values in JS provides quick access to data stored in objects for manipulation and makes a code more dynamic and flexible. In this tutorial we showed you the basic methods for looping through object keys and values. Mastering these techniques is essential for a developer looking to create complex and efficient applications. By constantly learning and exploring new techniques and resources, you will become more adept at working with objects in your code. Keep practicing and experimenting with different approaches to find the one that works best for your specific project.


Share