Register to get access to 15+ free programming courses with interactive exercises

Iterating over object properties JS: Objects

In JavaScript, objects, unlike arrays, are not a collection. It cannot be traversed like a normal array with the for..of loop, although doing something similar is sometimes necessary. For example, when we want to print all the properties on the screen, or when properties are added to an object dynamically - i.e., their names may change throughout an object's lifespan.

There are several ways to traverse objects in JavaScript. The easiest way is to use the for..in construct, which is very similar to a normal loop:

const course = { name: 'JS: React', slug: 'js-react' };
for (const prop in course) {
  console.log(`course.${prop} = ${course[prop]}`);
}
// course.name = 'JS: React'
// course.slug = 'js-react'

Despite how simple it may be to use, for..in does not work quite as it may seem. for..in visits not only the object own properties but also the properties of the prototype of that object (that is, inherited properties). We'll talk more about this topic later, but in a nutshell, objects in JavaScript can be interrelated, and accessing a property in one object can lead to (implicitly) accessing a property in another object (prototype). We've already seen this behavior in practice but avoided it so far.

What's important is that in the vast majority of cases this is undesirable behavior. This is why for..in is not commonly used. A much more common way is to traverse the keys. The Object.keys(obj) method creates an array of all the keys of the object:

const course = { name: 'JS: React', slug: 'js-react' };

const keys = Object.keys(course); // [ 'name', 'slug' ]

Then we can iterate over the key array and get the values we want. In practice, you usually get the key array first and do something with it. For example, filtering only the keys you need, and then processing the original object or creating a new one by getting the value of the key in the loop.

for (const key of keys) {
  console.log(course[key]);
}

If you don't need keys, you can get an array of the object's property values immediately with the Object.values(obj)method:

const course = { name: 'JS: React', slug: 'js-react' };

const values = Object.values(course); // [ 'JS: React', 'js-react' ]

for (const value of values) {
  console.log(value);
}

And the last one is a method that returns the key-value pairs of the object. I.e., each element itself will be an array containing the key and its corresponding value - [ key, value ]. The Object.entries(obj) method is responsible for this:

const course = { name: 'JS: React', slug: 'js-react' };

const entries = Object.entries(course);
// [[ 'name', 'JS: React' ], [ 'slug', 'js-react' ]]

It's easy to iterate over such an array with a for..of loop, and destructuring will make it look nice:

for (const [key, value] of entries) {
  console.log(key);
  console.log(value);
}

Let's look at an example. Let's implement the findKeys(), function, which returns a list of object keys whose value matches the one passed into the function:

const lessonMembers = {
  syntax: 3,
  using: 2,
  foreach: 10,
  operations: 10,
  destructuring: 2,
  array: 2,
};

findKeys(lessonMembers, 10); // ['foreach', 'operations']
findKeys(lessonMembers, 3);  // ['syntax']

The function logic is as follows:

  1. Traversing object properties
  2. If the value in the property is the same as the one we passed, then we add the key to the result
const findKeys = (obj, expectedValue) => {
  const result = [];

  const entries = Object.entries(obj);
  for (const [key, value] of entries) {
    if (value === expectedValue) {
      result.push(key);
    }
  }

  return result;
};

https://repl.it/@hexlet/js-objects-for-of-find-keys

Key order

One of the key features of an array is the strict order that the elements are in. This is not the case in objects, there is some order, but it cannot be controlled. This order is based on internal JavaScript rules. If an order is important to us, we will have to enter an additional array that will store the list of keys in the order we want them to be in.


Аватары экспертов Хекслета

Are there any more questions? Ask them in the Discussion section.

The Hexlet support team or other students will answer you.

For full access to the course you need a professional subscription.

A professional subscription will give you full access to all Hexlet courses, projects and lifetime access to the theory of lessons learned. You can cancel your subscription at any time.

Get access
130
courses
1000
exercises
2000+
hours of theory
3200
tests

Sign up

Programming courses for beginners and experienced developers. Start training for free

  • 130 courses, 2000+ hours of theory
  • 1000 practical tasks in a browser
  • 360 000 students
By sending this form, you agree to our Personal Policy and Service Conditions

Our graduates work in companies:

<span class="translation_missing" title="translation missing: en.web.courses.lessons.registration.bookmate">Bookmate</span>
<span class="translation_missing" title="translation missing: en.web.courses.lessons.registration.healthsamurai">Healthsamurai</span>
<span class="translation_missing" title="translation missing: en.web.courses.lessons.registration.dualboot">Dualboot</span>
<span class="translation_missing" title="translation missing: en.web.courses.lessons.registration.abbyy">Abbyy</span>
Suggested learning programs

From zero to a developer. Refunds in case you won't get a job

Frontend Developer icon
Profession
New
Development of front-end components for web applications
start anytime 10 months

Use Hexlet to the fullest extent!

  • Ask questions about the lesson
  • Test your knowledge in quizzes
  • Practice in your browser
  • Track your progress

Sign up or sign in

By sending this form, you agree to our Personal Policy and Service Conditions

Toto Image

Ask questions if you want to discuss a theory or an exercise. Hexlet Support Team and experienced community members can help find answers and solve a problem.