Understanding Object.entries()

Understanding Object.entries()

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

๐Ÿ‘‰ 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

ย