Press "Enter" to skip to content

Iterating in Javascript – Part 1: Objects and Maps

Objects

Using Object.keys() and Array.prototype.forEach() found in ECMAScript 5 we can iterate over an object. Object.keys creates an array that contains the properties of an object.

var obj = { first: "John", last: "Doe" };
Object.keys(obj).forEach(function(key) {
console.log(key, obj[key]);
});

ECMAScript 6 introduced for ... of, which we again can use with Object.keys to access the values of the properties.

for (const key of Object.keys(obj)) {
console.log(key, obj[key]);
}

ECMAScript 8 adds Object.entries() which creates an array that contains the key and value pairs:

Object.entries(obj).forEach(
([key, value]) => console.log(key, value)
);

Also added in ECMAScript 8 is Object.values(), this returns an array of values of all enumerable property values of the object. Do note that it does not return the key.

Both Object.keys() and Object.entries() iterate properties in the same order as a for...in loop but ignore the prototype chain. Only the object’s own enumerable properties are iterated. A for...in loop can also be used to iterate over enumerable properties of JavaScript objects. This loop does include inherited properties from prototype chain. We can combine it with the hasOwnProperty() method to check for direct properties.

for (const key in obj) {
//optional check for properties from prototype chain
if (obj.hasOwnProperty(key)) {
console.log(key, obj[key]) 
}
}

The Object.getOwnPropertyNames() method returns an array of all properties (including non-enumerable properties. To check for direct properties only it can be combined with the hasOwnProperty() method as in the example above.

More information and sources

Maps

Map: introduced in ECMAScript 6, Maps are a data collection type that store data in a form of pairs which contain a unique key and a value mapped to that key. Object and Map are based on the same concept but there are differences.
– The key in Map can be any data type vs String and Symbol in Object.
– in Map the order elements is preserved, in Object it is not.
Map is an instance of Object.
Map is built-in iterable  — Object is not.

Using for...of:

var map = new Map(); //Empty Map
var map = new Map([[1,'a'],[2,'b']]); // map = {1=>2, 2=>3}

for (const item of map){
console.log(item);
//Array[1,'a']
//Array[2,'b']
}

for (const [key,value] of map){
console.log(`key: ${key}, value: ${value}`);
}

Map also has a built-in forEach() method

map.forEach((value, key) => console.log(`key: ${key}, value: ${value}`));

More information and sources

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *