Home » JavaScript Tutorial

How to iterate over a JavaScript Object?

JavaScript objects: Here, we are going to learn how to iterate over a JavaScript object? How to iterate an object in JavaScript?
Submitted by Siddhant Verma, on December 14, 2019

Time and again you may feel the need to traverse through an object to find out a particular property, a certain value corresponding to a key or maybe make changes to that object's certain key and values. In arrays, it's pretty simple and we have some flexible methods to iterate over them such as the regular for loop, the forEach loop, etc. When it comes to objects, the simplest way to iterate over an object is the for-in loop.

Consider the following object,

const student1={
	name: 'Ryan',
	age: 15,
	subject: 'Science',
	rank: 17
}
console.log(student1);

Output

{name: "Ryan", age: 15, subject: "Science", rank: 17}

We can use the for-in loop to iterate over the properties or the keys of our student1 object. Inside the loop, we'll first check if the property belongs solely to our object and only then we'll output it and it's value to the console,

function iterateObj(Obj) {
    for (prop in Obj) {
        if (Obj.hasOwnProperty(prop)) {
            console.log(`${prop} : ${Obj[prop]}`)
        }
    }
}
iterateObj(student1);

Output

name : Ryan
age : 15
subject : Science
rank : 17

This is a simple way to iterate over the object. We can also use the for-in loop to only print the keys, the values or both key-values as we did above.

Looping through an object sounds unconventional because we generally associate iterating over an element with an array. ES6 introduced three methods that we can use which help us converting the object into an array and then we can easily loop through it the way we'd do in an array.

We can use Object.keys() to convert all our keys of the object into an array of keys.

const studKeys = Object.keys(student1);
console.log(studKeys);

Output

(4) ["name", "age", "subject", "rank"]

We get an array back with some keys inside it. Let's try to loop through it,

studKeys.forEach(k => console.log(k));

Output

name
age
subject
rank

Similarly, we can get an array with all the values of our object using Object.values() method,

const studVal = Object.values(student1);
console.log(studVal);

Output

(4) ["Ryan", 15, "Science", 17]

And again, we can iterate over this array using a normal for loop too.

for (let i = 0; i < studVal.length; i++) {
    console.log(studVal[i]);
}

Output

Ryan
15
Science
17

But what if we want both the key and it's corresponding value together as a pair inside an array? It'd be great if we could have an array of arrays for this, then we'd easily loop overusing the forEach loop.

We can simply use the Object.entries() method which converts the key-value pairs into individual arrays and combines them or wraps them together inside another array.

const student = Object.entries(student1);
console.log(student);

Output

(4) [Array(2), Array(2), Array(2), Array(2)]
    0: (2) ["name", "Ryan"]
    1: (2) ["age", 15]
    2: (2) ["subject", "Science"]
    3: (2) ["rank", 17]
    length: 4
    __proto__: Array(0)

We now get an array with another array having the key and value as separate elements for each index. We can get to any key-value property using the first indexing and use the 0th index to get the key and 1st index to get its value. Let's use the forEach method to loop or iterate over the object that we just converted into a 2D array.

student.forEach(s => console.log(`${s[0]} : ${s[1]}`));

Output

name : Ryan
age : 15
subject : Science
rank : 17

Thus we can either use the for-in loop to iterate over an object or first convert it into an array and then iterate over the object as if we're iterating over an array.







Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.