How to use Object.entries() in JavaScript

Let's dive into Object.entries(), what it is, and how it can be beneficial.

What is Object.entries()?

Object.entries() is a method that gives you an array of pairs (another array) from an object. Each pair consists of its key and its associated value.

It's like getting a list where both the key and value of each item are shown together.

It's easier than I'm probably making it sound...

So lets look at an example:

How it works

Consider you have an object like this:

const jediDetails = {
  name: 'Luke Skywalker',
  affiliation: 'Rebel Alliance',
  rank: 'Jedi Knight'
};

When you use Object.entries(jediDetails), you'll receive a list of pairs:

[ ['name', 'Luke Skywalker'], ['affiliation', 'Rebel Alliance'], ['rank', 'Jedi Knight'] ]

As you can see, you get an array of arrays with the key and values.

Why Use Object.entries()?

There's many use cases for Object.entries() but here's a couple of the big reasons:

  • Detailed Overview: It provides a comprehensive view of an object, showing both names and values.
  • Structured Data: The paired format can be especially useful when you want to work with data in a structured way, like in loops or when mapping data.

Happy coding! 🎉

JSJavaScript
Avatar for Niall Maher

Written by Niall Maher

Founder of Codú - The web developer community! I've worked in nearly every corner of technology businesses; Lead Developer, Software Architect, Product Manager, CTO and now happily a Founder.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.