Rehan Sattar
Rehan Sattar

Follow

Rehan Sattar

Follow
Understanding Object.entries()

Understanding Object.entries()

A quick guide to understanding `Object.entries()`

Rehan Sattar 's photo
Rehan Sattar
·Jun 23, 2021
Play this article

👉 The Object.entries() method is used to return a 2D array consisting of enumerable property [key, value] pairs of the object. It creates a pair of all of your object's properties and their respective values.

let's take a look at the syntax.

Object.entries(object);

👉 Here are some of the major points you have to remember while using Object.entries()

  1. It loops in the same order as a for...in loop does.

  2. One important difference is that a for...in loop enumerates properties in the prototype chain as well.

  3. The order of the array returned by Object.entries() does not depend on how an object is defined. You can always sort the array based on your own criteria using .sort() on the returned array.

  4. Object.entries is such a useful method when you need both a key and value at the same time. You can let go of the traditional approach of for...in or for loop.

Examples:

👉 Basic Usage

// Basic example: 
const user = {
  name: 'Mike',
  age: 30,
}

Object.entries(user) // Output: [ ['name', 'Mike'], ['age', 30] ]

👉 Looping approaches

const user = {
  firstName: 'John',
  lastName: 'Wick',
  age: 30,
  isActive: false,
}

// Traditional  approach using `for...in` loop
for (let key in user) {
    console.log(`${key}: ${user[key]}`)
}

// Using `Object.entries()`
Object.entries(user).forEach((item) => {
 console.log(`${item.key}: ${item.value}`
}))

// 👉  Output in  both cases: 
/* 
  firstName: John
  lastName: Wick
  age: 30
  isActive: false
*/

You can also use the power of destructuring in javascript to make it easier to understand.

// With array destructuring
Object.entries(user).forEach(([key, value]) => console.log(`${key}: ${value}`))

That's it, folks! hope it was a good read for you. Thank you! ✨

👉 References:

The official documentation of Object.entries()

👉 Follow me: Github Twitter LinkedIn Youtube

Did you find this article valuable?

Support Rehan Sattar by becoming a sponsor. Any amount is appreciated!

See recent sponsors | Learn more about Hashnode Sponsors
 
Share this