Object.entries

By  on  

Navigating and managing data structures is a really important skill for every level of engineer to have and improve upon. Over the years, the JavaScript language has continued to provide more methods for managing data structures, from Object.keys to Object.values and so on. One of my favorites is Object.entries, an API that provides the keys and values via an array of arrays. Let's have a look!

Consider the following object:

const obj = {
    name: "David",
    color: "green",
    balance: 100
}

Traditionally we'd have iterated over keys via a for loop, then use array syntax to get values:

const obj = {
    name: "David",
    color: "green",
    balance: 100
}

for (const key in obj) {
    const value = obj[key];
}

We do have Object.keys() and Object.values() to get each now, but neither method provides a relationship to the parent key or value. I really love using Object.entries to maintain that relationship and get both the key and value:

Object.entries({
    name: "David",
    color: "green",
    balance: 100
}).forEach(([key, value]) => console.log(key, value))

/*
name David
color green
balance 100
*/

Object.entries is such a useful method when you need both a key and value. Throw away those old for loops and Array-like syntaxes and use Object.entries like a pro!

Recent Features

  • By
    I’m an Impostor

    This is the hardest thing I've ever had to write, much less admit to myself.  I've written resignation letters from jobs I've loved, I've ended relationships, I've failed at a host of tasks, and let myself down in my life.  All of those feelings were very...

  • By
    CSS Gradients

    With CSS border-radius, I showed you how CSS can bridge the gap between design and development by adding rounded corners to elements.  CSS gradients are another step in that direction.  Now that CSS gradients are supported in Internet Explorer 8+, Firefox, Safari, and Chrome...

Incredible Demos

  • By
    Reverse Element Order with CSS Flexbox

    CSS is becoming more and more powerful these days, almost to the point where the order of HTML elements output to the page no longer matters from a display standpoint -- CSS lets you do so much that almost any layout, large or small, is possible.  Semantics...

  • By
    Introducing MooTools Templated

    One major problem with creating UI components with the MooTools JavaScript framework is that there isn't a great way of allowing customization of template and ease of node creation. As of today, there are two ways of creating: new Element Madness The first way to create UI-driven...

Discussion

  1. I had a big discussion on this over at StackOverflow : https://stackoverflow.com/q/66074709/126833

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!