JavaScript Iterating Object In 2 Ways

We know that Object is non-primitive data type is basically stores data in key-value pairwise.  In object, we can store everything you can name it like another object, array, functions, etc. As we store data, we need to iterate object to read and manipulate Object.

For array, everyone knows that, JavaScript offers a range of looping options to choose. But very few are aware of that, we can also iterate Object in various ways and their pros/cons. So, we will discuss mainly Two of them today with proper examples:

Table of Contents

  1. Iterating Object In JavaScript In Traditional way
  2. Iterating Object In JavaScript In ES6 way

Iterating Object In JavaScript In a Tradition way

const webName = {
    firstName: 'shouts',
    lastName: 'dev',
};

const keyArray = []
const valueArray = []
const keyValueArray = []
for (const key in webName) {
    keyArray.push(key)
    valueArray.push(webName[key])
    keyValueArray.push([key, webName[key]])
}
console.log(keyArray);  \\ [ 'shouts', 'dev' ] 
console.log(valueArray); \\ [ 'firstName', 'lastName' ]
console.log(keyValueArray); \\ [ [ 'firstName', 'shouts' ], [ 'lastName', 'dev' ] ]

In the above example, we basically, iterated over object  named webName by use for…in loop. Though all know that for…in is made for iterating object, we can't get the object's property value directly. For this, we have to access the object's property value by bracket notation first.

Moreover, if want to apply array methods to that property value we have to take a new array and push into it in every loop. Which in case, may rise complexity. Also, the for...in loop returns all properties and inherited properties for an array or array-like object, which can lead to unexpected behavior.

Iterating Object In JavaScript In ES6 way

To get rid of all those, ECMA introduced 3 new Object utility functions in ES6 and ES7. By those, we can do the same above with ease and less effort.

The most advantage of those methods is that, those methods by default return a array doesn’t follow the prototype chain and only iterates over the values that are directly in the provided object. Those methods are:

  1. Object.keys() → takes an object and returns all of the keys in an array
  2. Object.values() → takes an object and returns all of the values of in an array
  3. Object.entries() → takes an object and returns all of the key-value pairs in an array

See the code snippet below to get the idea:

const webName = {
    firstName: 'shouts',
    lastName: 'dev',
};

console.log(Object.values(webName)); \\ [ 'shouts', 'dev' ] 
console.log(Object.keys(webName));  \\ [ 'firstName', 'lastName' ]
console.log(Object.entries(webName));  \\[ [ 'firstName', 'shouts' ], [ 'lastName', 'dev' ] ]

That's all for today. If any questions peeping into your mind, feel free to put them in the comment box and we will get back to you as soon as possible.