Flexiple Logo
  1. Home
  2. Blogs
  3. JavaScript
  4. Loop Through an Object In JavaScript – How to Iterate Over an Object in JS

Loop Through an Object In JavaScript – How to Iterate Over an Object in JS

Author image

Siddharth Khuntwal

Software Developer

Published on Wed May 15 2024

To loop through an object in JavaScript, developers utilize various methods to iterate over properties. JavaScript objects store data as key-value pairs. To access these values, programmers commonly use the `for...in` loop, which allows them to execute a block of code for each property in the object. Another method involves `Object.keys()`, which returns an array of a given object's own enumerable property names, followed by a loop to access values. Developers choose `Object.values()` to retrieve an array of values from the object directly. If both keys and values are needed, `Object.entries()` serves well by providing an array of arrays, each containing a key paired with its corresponding value. Developers select the appropriate method based on the specific requirements of their code.

How to Loop Through an Object In JavaScript With a for…in loop

To loop through an object in JavaScript using a for...in loop, you need to access each property and its value. A for...in loop iterates over the enumerable properties of an object. JavaScript treats each property as a string in the loop. This method checks every property in the object. Declare a variable in the loop to capture each property key.

Here’s a basic example:

const person = {
    name: "John",
    age: 30,
    city: "New York"
};

for (let key in person) {
    console.log(key + ": " + person[key]);
}

In this code, key variable receives the property name during each iteration. JavaScript prints each property and its corresponding value to the console. Ensure properties not intended for enumeration are not included by checking if the object itself owns the property using hasOwnProperty. This method prevents the loop from accessing inherited properties.

Example of using hasOwnProperty:

const person = {
    name: "John",
    age: 30,
    city: "New York"
};

for (let key in person) {
    if (person.hasOwnProperty(key)) {
        console.log(key + ": " + person[key]);
    }
}

Use a for...in loop if you need to execute a block of code for each property. This loop works efficiently for objects with multiple properties. Remember, arrays are also objects, but using a for...in loop on arrays might yield unexpected property keys, as arrays inherit from Array.prototype. Always prefer array-specific methods like forEach or for...of for array iterations, unless you have a specific reason to use a for...in loop.

How to loop through an object in JavaScript with object static methods

To loop through an object in JavaScript using object static methods, developers often utilize Object.keys(), Object.values(), and Object.entries(). Each method serves a specific purpose and provides a unique way to access data stored in an object.

Using Object.keys(obj) Method

To loop through an object in JavaScript with object static methods, developers often utilize Object.keys(obj). This method returns an array of a given object's own enumerable property names, iterated in the same order that a normal loop would. For example, if you have an object person with properties name and age, Object.keys(person) will return ['name', 'age'].

Once you have the keys, you can loop over them using a standard for loop. This method ensures that each key is accessed, and the corresponding value can be retrieved using bracket notation. For instance:

const person = { name: 'Alice', age: 25 };
const keys = Object.keys(person);
for (const key of keys) {
    console.log(key + ': ' + person[key]);
}

This will output:

name: Alice
age: 25

Object.keys(obj) provides a robust way to access keys in objects that do not have inherited enumerable properties. This approach is particularly useful when dealing with objects where the key names are not known beforehand, or where the object keys need to be dynamically processed.

Using Object.values(obj) Method

To loop through an object in JavaScript using object static methods, developers often use Object.values(). This method extracts all property values from an object and returns them in an array. To iterate over the array, JavaScript provides several loop constructs such as for, for...of, or forEach().

Using Object.values(obj), where obj represents the object to be iterated, JavaScript simplifies access to each value. Here is a code example demonstrating this method:

const obj = { a: 'Apple', b: 'Banana', c: 'Cherry' };
const values = Object.values(obj);

for (const value of values) {
    console.log(value);
}

In the above example, Object.values(obj) extracts the values 'Apple', 'Banana', and 'Cherry' from obj. The for...of loop then iterates over each item in the values array and outputs them to the console. This approach ensures that each value within the object is accessed sequentially.

Using Object.entries(obj) Method

To loop through an object in JavaScript using Object.entries(), developers access both keys and values simultaneously. Object.entries() converts the object into an array of [key, value] pairs, enabling iteration with array methods. For each loop iteration, the array method forEach executes a provided function once per array element.

Here is a practical example of using Object.entries():

const person = {
    name: 'John',
    age: 30,
    occupation: 'Engineer'
};

Object.entries(person).forEach(([key, value]) => {
    console.log(`${key}: ${value}`);
});

In this code, Object.entries(person) converts the person object into an array of arrays. Each inner array contains two elements: the key and the value of one property of the object. The forEach loop then executes the arrow function, printing each key and value to the console.

Object.entries() proves effective for debugging purposes, allowing developers to easily inspect object contents. Additionally, developers use Object.entries() for data transformation tasks, such as converting objects into different formats or filtering content based on specific conditions. Modify the output format or add filtering logic in the forEach loop if specific data manipulation is required.

How To Loop Through an Object In JavaScript Using Lodash _.forOwn() Method

To loop through an object in JavaScript using the Lodash _.forOwn() method, start by including the Lodash library in your project. Lodash's _.forOwn() method allows developers to iterate over an object's own enumerable string-keyed properties. This method provides a callback function that executes for each property in the object. In the callback, the first argument represents the value of the property, and the second argument represents the key.

Install Lodash using npm with the command npm install lodash. Import the necessary _.forOwn() function from Lodash at the beginning of your JavaScript file with import _ from 'lodash';. Here is an example of how to use _.forOwn() to print each key-value pair of an object:

import _ from 'lodash';

const user = {
  name: 'John Doe',
  age: 30,
  isActive: true
};

_.forOwn(user, (value, key) => {
  console.log(key + ': ' + value);
});

In this example, the console will output the name, age, and isActive status of the user. Developers prefer _.forOwn() because it automatically excludes inherited properties from the prototype chain. This ensures that the loop focuses only on the object's own properties. Use _.forOwn() if the order of iteration is not critical since the order of enumeration is not guaranteed. Remember to handle complex objects carefully; deeply nested objects require additional logic to iterate through each level effectively. Lodash provides robustness and clarity, enhancing code readability and maintenance.

Conclusion

To iterate over an object in JavaScript, developers have several reliable methods at their disposal. Each technique, whether using a for...in loop, Object.keys(), Object.values(), or Object.entries(), offers specific advantages depending on the application's needs. JavaScript provides the flexibility to access properties and values efficiently, ensuring that the code remains clean and maintainable. Developers improve script performance and readability by choosing the appropriate iteration method. Opt for Object.keys() to retrieve property names, use Object.values() for values, or select Object.entries() to work with entries if the context demands both property names and values. Always ensure to implement error-checking or conditional structures, like including a hasOwnProperty check, if the situation involves potential inherited properties.

Related Blogs

Browse Flexiple's talent pool

Explore our network of top tech talent. Find the perfect match for your dream team.