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
    Creating Scrolling Parallax Effects with CSS

    Introduction For quite a long time now websites with the so called "parallax" effect have been really popular. In case you have not heard of this effect, it basically includes different layers of images that are moving in different directions or with different speed. This leads to a...

  • By
    5 Awesome New Mozilla Technologies You’ve Never Heard Of

    My trip to Mozilla Summit 2013 was incredible.  I've spent so much time focusing on my project that I had lost sight of all of the great work Mozillians were putting out.  MozSummit provided the perfect reminder of how brilliant my colleagues are and how much...

Incredible Demos

  • By
    Using Dotter for Form Submissions

    One of the plugins I'm most proud of is Dotter. Dotter allows you to create the typical "Loading..." text without using animated images. I'm often asked what a sample usage of Dotter would be; form submission create the perfect situation. The following...

  • By
    Morphing Elements Using MooTools and CSS

    Morphing an element between CSS classes is another great trick the MooTools JavaScript library enables you to do. Morphing isn't the most practical use of MooTools, but it's still a trick at your disposal. Step 1: The XHTML The block of content that will change is...

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!