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
For checking existence of property and requires iterating through property only we can make use of Object.keys(obj) method.
For validating property values and requires iterating through property values only we can make use of Object.values(obj) method.
For mapping through property and property values we can make use of Object.entries(obj) method.
Happy coding!