DEV Community

Ravina Deogadkar
Ravina Deogadkar

Posted on

1

Javascript: iterating object

Objects in Javascript is similar to dictionary with key value pair value. Within the project development process we need to deal with the iteration of object. Let's look at different ways for iterating.

for...in

The traditional for...in loop works bit different for objects than arrays. For...in loop enumerates through the object's it's own property.

let person={name:"Ravina", age:25, country:"India"}

for(let data in person){ console.log(${data}: ${person[data]});}

Object class provides other methods that we can use for iterating over an object.

Object.entries(obj)

Object.entries(obj) return an array of it's own object enumerated string-keyed property [key, value] pair returned in the same way as provided by for...in loop. The order of an array returned by entries() method is same as the object defined.

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

Object.keys(obj)

Object.keys(obj) returns an array of an object's own enumerated property and iterated in the same way as that in loop. The array returned by keys is iterated in the same way as given by looping over the properties of an object manually.

for(let key in Object.keys(person)){ console.log(${key}: ${person[key]});}

Object.values(obj)

Object.values(obj) return an array of object's own enumerated property values and iterated in the same order as that of for...in loop.The array returned by keys is iterated in the same way as given by looping over the property values of an object manually.

for(let value in Object.values(person)){ console.log(${value});}

When to use what

  1. For checking existence of property and requires iterating through property only we can make use of Object.keys(obj) method.

  2. For validating property values and requires iterating through property values only we can make use of Object.values(obj) method.

  3. For mapping through property and property values we can make use of Object.entries(obj) method.

Happy coding!

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay