DEV Community

How to loop through object - JavaScript

Mohamed Ibrahim on January 28, 2023

In this article we will learn how to loop through object. It is very common to iterate over an object in JavaScript. There is more than one way t...
Collapse
 
jankapunkt profile image
Jan Küster

Note that there are different scopes for these loops.

for..in

The for...in statement iterates over all enumerable string properties of an object (ignoring properties keyed by symbols), including inherited enumerable properties.

Object.keys

The Object.keys() static method returns an array of a given object's own enumerable string-keyed property names.

Depending on the objects structure you may get totally different (and unexpected) results.

Collapse
 
moibra profile image
Mohamed Ibrahim

Thanks for sharing, that's very helpful

Collapse
 
Sloan, the sloth mascot
Comment deleted
Collapse
 
moibra profile image
Mohamed Ibrahim • Edited

Thank you Abhay

Collapse
 
parthprajapati profile image
Parth

Nice one :) Earlier looked for some similar and easy to understood tut, but couldn't find it. Thanks

Collapse
 
moibra profile image
Mohamed Ibrahim • Edited

You're welcome :)

Collapse
 
catherineisonline profile image
Ekaterine Mitagvaria

Nice post, thank you!

Collapse
 
moibra profile image
Mohamed Ibrahim

Thank you Ekaterina

Collapse
 
vulcanwm profile image
Medea

this is really helpful!

Collapse
 
moibra profile image
Mohamed Ibrahim

Thank you Medea

Collapse
 
scriptneutron profile image
script-neutron

Using entries seems a hustle 😅

Collapse
 
dservnh profile image
dserv-nh

It's really not if you just need the key/value pairs. See the MDN Example

const object1 = {
  a: 'somestring',
  b: 42
};

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

// Expected output:
// "a: somestring"
// "b: 42"
Enter fullscreen mode Exit fullscreen mode