Object Iteration ways in JavaScript

Fatemeh Paghar - Apr 8 - - Dev Community

JavaScript, being a versatile language, offers several ways to iterate over objects. In this article, we'll explore various techniques for iterating over objects, providing examples to deepen your understanding.

1-for...in Loop:

The for...in loop is the most traditional way to iterate over the properties of an object. It iterates over all enumerable properties, including those inherited through the prototype chain. However, caution is required when using it with objects that may have properties added to their prototypes.

const obj = { a: 1, b: 2, c: 3 };
for (let prop in obj) {
    console.log(prop + ': ' + obj[prop]);
}
Enter fullscreen mode Exit fullscreen mode

Avoid iterating over inherited properties by using the hasOwnProperty() method.

for (let prop in obj) {
    if (obj.hasOwnProperty(prop)) {
        console.log(prop + ': ' + obj[prop]);
    }
}
Enter fullscreen mode Exit fullscreen mode

2-Object.keys():

The Object.keys() method returns an array of a given object's enumerable property names. It's a convenient way to iterate over object properties when you're only interested in keys.

const obj = { a: 1, b: 2, c: 3 };
Object.keys(obj).forEach(key => {
    console.log(key + ': ' + obj[key]);
});

Enter fullscreen mode Exit fullscreen mode

Remember that Object.keys() ignores inherited properties.

3-Object.entries():

Object.entries() returns an array of a given object's own enumerable string-keyed property [key, value] pairs. This method allows you to iterate over both keys and values simultaneously.

const obj = { a: 1, b: 2, c: 3 };
Object.entries(obj).forEach(([key, value]) => {
    console.log(key + ': ' + value);
});
Enter fullscreen mode Exit fullscreen mode

Keep in mind that this method doesn't work with symbols as keys.

4-Object.values()

The Object.values() method takes an object as its parameter and returns an array containing the property values of that object. It ignores properties inherited through the prototype chain and includes only the object's own enumerable properties.

const obj = { a: 1, b: 2, c: 3 };
const values = Object.values(obj);
console.log(values); // Output: [1, 2, 3]
Enter fullscreen mode Exit fullscreen mode

In this example, Object.values(obj) returns an array [1, 2, 3] containing the values of the properties a, b, and c.

Iterating Over Values:
Once you have the array of values, you can iterate over it using any array iteration method like forEach, map, for...of, etc.

const obj = { a: 1, b: 2, c: 3 };
const values = Object.values(obj);
values.forEach(value => {
    console.log(value);
});
Enter fullscreen mode Exit fullscreen mode

This code snippet logs each value (1, 2, 3) to the console.

It's important to note that Object.values() only returns the values of properties with string keys. Properties with non-string keys, such as symbols, are ignored.

const obj = { a: 1, [Symbol('b')]: 2, c: 3 };
const values = Object.values(obj);
console.log(values); // Output: [1, 3]
Enter fullscreen mode Exit fullscreen mode

In this example, the property with the symbol key Symbol('b') is ignored, and only the values of properties a and c are returned.

5-Object.getOwnPropertyNames()

Object.getOwnPropertyNames() is a method in JavaScript used to iterate over the properties of an object. Unlike methods like Object.keys() or for...in loops, which only iterate over enumerable properties, Object.getOwnPropertyNames() returns an array of all property names found directly on the given object, regardless of their enumerability.

Here's how you can use Object.getOwnPropertyNames() to iterate over an object:

const obj = {
    a: 1,
    b: 2,
    c: 3
};

const properties = Object.getOwnPropertyNames(obj);

properties.forEach(property => {
    console.log(property + ': ' + obj[property]);
});

Enter fullscreen mode Exit fullscreen mode

One important aspect to note is that Object.getOwnPropertyNames() includes both enumerable and non-enumerable properties of the object. Enumerable properties are those that can be iterated over using methods like for...in or Object.keys(), while non-enumerable properties cannot be iterated over by default.

Consider the following example:

const obj = {};
Object.defineProperty(obj, 'nonEnumProp', {
    value: 'Non-enumerable property',
    enumerable: false
});

const properties = Object.getOwnPropertyNames(obj);
console.log(properties); // Output: ["nonEnumProp"]
Enter fullscreen mode Exit fullscreen mode

In this example, we define a property nonEnumProp on obj with the enumerable property set to false. Despite being non-enumerable, nonEnumProp is included in the array returned by Object.getOwnPropertyNames(). This behavior sets Object.getOwnPropertyNames() apart from methods like Object.keys(), which only return enumerable properties.

Conclusion

In this article, we've explored various effective methods for iterating through objects in JavaScript, each tailored to specific requirements. These methods provide flexibility and control over the iteration process, ensuring efficient navigation and manipulation of object properties. Whether using for...in loops for basic enumeration, Object.keys() for accessing keys, or custom iterators with Symbol.iterator for advanced control, JavaScript offers a diverse toolkit for object iteration. By understanding and leveraging these methods, developers can enhance code readability, maintainability, and performance, ultimately contributing to the creation of more robust and efficient applications.

References

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .