Looping through objects in javascript

Looping through objects in javascript

ยท

2 min read

In this post I will explain you the various methods to loop through objects in javascript programming language.

for . . . in

  • This approach is used to loop through the keys of an object
  • By looping through the keys, you can get the value using object[key]
const object = {
  name: "Dhanush",
  language:"js"
}

for(const key in object){
  const value = object[key]
  console.log("Key: ",key)
  console.log("Value: ",value)
}

// Key: name
// Value: Dhanush
// Key: language
// Value: js

Object.keys()

  • The keys method of the Object constructor returns an array of the keys in an object
  • With the array of keys you can then loop through the array using any array approaches.
  • You can get the value fo the objects key also using object[key]
const object = {
  name: "Dhanush",
  language:"js"
}
const keys = Object.keys(object)
// ['name', 'language']
keys.forEach(function(key){
  const value = object[key]
  console.log("Key: ",key)
  console.log("Value: ",value)
})

// Key: name
// Value: Dhanush
// Key: language
// Value: js

Object.values()

  • The values method returns an array of the values in an object ( opposite to keys method )
  • With the array got you can loop through them using any array functionality
  • You can use a key to get a value directly but you cannot use a value to get a key directly
const object = {
  name: "Dhanush",
  language:"js"
}
const values = Object.values(object)
// ['Dhanush', 'js']
values.forEach(function(value){
  console.log(value)
})

// Dhanush
// js

Object.entries()

  • The entries method returns an array of subarrays where each subarray has two items, the first one being the key and the second one being the value
  • Unlike the keys and values method, entries returns the keys and values of an object in subarrays.
  • Then you can access them using the index.
const object = {
  name: "Dhanush",
  language:"js"
}
const entries = Object.entries(object)
// [
//   ['name', 'Dhanush'],
//   ['language', 'js'],
// ]
entries.forEach(function(entry){
  const key = entry[0]
  const value = entry[1]
  console.log("Key: ",key)
  console.log("Value: ",value)

console.log(value)
})

// Key: name
// Value: Dhanush
// Key: language
// Value: js

Twitter post ๐Ÿ‘‡

Thanks for reading ๐Ÿ™

Hope you liked this post, If you have any questions please feel free to reach out to me via Twitter

Leave a like & follow for more โœŒ๏ธ

Did you find this article valuable?

Support Dhanush N by becoming a sponsor. Any amount is appreciated!