The Object.fromEntries Method

Published: Friday, July 22, 2022

Greetings, friends! Have you ever wanted to turn an array of two elements into an object with key-value pairs from those elements? Or, maybe you wanted to create a new object from an existing one but with the values transformed. Using the power of the Object.fromEntries method, we can do both of these things easily!

The Object.fromEntries Syntax

The Object.fromEntries method accepts one parameter, an iterable such as Arrays, Strings, Maps, and Sets.

javascript
Copied! ⭐️
Object.fromEntries(iterable);

This method will return a new object whose properties are given by the "entries" of the iterable. If you've used the Object.entries method before, then this may be familiar to you. An entry can be thought of as a [key, value] pair.

Converting Two-Element Arrays into Objects

The Object.fromEntries method can be used with an array of two-element arrays and will return a new object. The first element of these two-element arrays will be the property key, and the second element will be the property value.

javascript
Copied! ⭐️
const arr = [
  ['pizzas', 1],
  ['donuts', 2],
  ['potatoes', 3]
];

const obj = Object.fromEntries(arr);

console.log(obj);
// OUTPUT: { pizzas: 1, donuts: 2, potatoes: 3 }

Transforming Objects

As mentioned on MDN, the Object.fromEntries method can be thought of as the "reverse" of the Object.entries method we discussed in the previous article.

javascript
Copied! ⭐️
const obj1 = { a: 1, b: 2, c: 3 };

const obj2 = Object.fromEntries(
  Object.entries(obj1)
  .map((entry) => [ entry[0], entry[1] * 2 ])
);

console.log(obj2);
// OUTPUT: { a: 2, b: 4, c: 6 }

We are using Object.entries to get an array of key-value pairs from obj1. We are using the Array.map method to return a new array with a modified property value. Then, we are using Object.fromEntries to transform these new key-value pairs back into an object.

We can actually use array destructuring to make the code a bit cleaner.

javascript
Copied! ⭐️
const obj1 = { a: 1, b: 2, c: 3 };

const obj2 = Object.fromEntries(
  Object.entries(obj1)
  .map(([ key, val ]) => [ key, val * 2 ])
);

console.log(obj2);
// OUTPUT: { a: 2, b: 4, c: 6 }

We didn't have to use Object.fromEntries to transform an object's property values. We could have used Object.keys with an Array.forEach method instead.

javascript
Copied! ⭐️
const obj1 = { a: 1, b: 2, c: 3 };

Object.keys(obj1).forEach(key => {
  obj1[key] = obj1[key] * 2;
})

console.log(obj1);
// OUTPUT: { a: 2, b: 4, c: 6 }

However, this approach modifies the original object. This may or may not be what you want. If you want to create a new object with transformed property keys or values, then using the earlier approach with Object.fromEntries and Object.entries is probably the better alternative.

Using Object.fromEntries with Custom Iterables

As mentioned in my tutorial on iterators and iterables, we can create custom iterables ourselves. It's easy to create custom iterables using generators.

javascript
Copied! ⭐️
const createNewIterable = (length) => {
  return {
    *[Symbol.iterator]() {
      let value = 10;
      let currentLetter = 'a';
      const nextLetter = (letter) =>
        String.fromCharCode(letter.charCodeAt(letter.length - 1) + 1);

      while (value <= length * 10) {
        yield [currentLetter, value];
        value = value + 10;
        currentLetter = nextLetter(currentLetter);
      }
    }
  }
}

const customIterable = createNewIterable(5);
Object.fromEntries(customIterable);
// OUTPUT: { a: 10, b: 20, c: 30, d: 40, e: 50 }

As mentioned on MDN, the Object.fromEntries method requires that an "iterable argument is expected to be an object that implements an @@iterator method, that returns an iterator object, that produces a two element array-like object, whose first element is a value that will be used as a property key, and whose second element is the value to associate with that property key."

We can implement the @@iterator method by using Symbol.iterator as shown in the code snippet above. A generator function inherently creates an iterator object. We are using the yield keyword to produce two-element arrays. This fulfills all the requirements to make the Object.fromEntries method happily accept our custom iterable.

Conclusion

In this tutorial, we have seen how to use Object.fromEntries to turn an array of two elements into an object with key-value pairs from those elements. We can also create a new object from an existing one but with modified property keys or values. For advanced use cases, we can even create our own custom iterables and pass them into Object.fromEntries!

Resources