JavaScript fromEntries method ES10

JavaScript , , , 0 Comments

In this article, we are gonna talk about JavaScript fromEntries method. fromEntries introduced in ES10/2019 and it is an object method, we will cover basics and different types of examples.

Let’s start, Object.fromEntries is a very useful built-in JavaScript method that transforms a list of key-value pairs into an object. Let’s see the quick basic example below:

const entries = [
  ['foo', 'bar'],
  ['baz', 42]

const obj = Object.fromEntries(entries);
// expected output: Object { foo: "bar", baz: 42 }

In the above example we have converted a paired array of array into an object. So basically Object.fromEntries does that. I was playing with that and found that If you pass a simple array into Object.fromEntries It will give you an error Uncaught TypeError: Iterator value x is not an entry object, let’s see an example below:

Object.fromEntries(['x', 42, 'y', 50])
// output: Uncaught TypeError: Iterator value x is not an entry object



Return value

JavaScript fromEntries returns a new object whose properties are given by the entries of the iterable.

Don’t misunderstand it with Object.entries method, The new Object.fromEntries API performs the inverse of Object.entries. To easily reconstruct an object based on its entries. See the comparision between them:

const object = { x: 42, y: 50 };
const entries = Object.entries(object);
// → [['x', 42], ['y', 50]]

const result = Object.fromEntries(entries);
// → { x: 42, y: 50 }

Converting a Map to an Object

Using Object.fromEntries you can easily convert map to object. See the example below:

const map = new Map([ ['foo', 'bar'], ['baz', 42] ]);
const obj = Object.fromEntries(map);
console.log(obj); // { foo: "bar", baz: 42 }

Warning: beware of data loss with fromEntries method

When converting maps into plain objects, there’s an implicit assumption that each key stringifies uniquely. If this assumption does not hold, and data loss occurs:

const map = new Map([
  [{}, 'a'],
  [{}, 'b'],
// → { '[object Object]': 'b' }

Note: the value ‘a’ is nowhere to be found, since both keys stringify to the same value of ‘[object Object]’.


Object transformations

Using Object.fromEntries you can easily transform objects like an example below:

const object1 = { a: 1, b: 2, c: 3 };

const object2 = Object.fromEntries(
  .map(([ key, val ]) => [ key, val * 2 ])

// { a: 2, b: 4, c: 6 }


fromEntries() 73 No 63 12.1 60

I hope it was useful, If I have missed anything else please let me know. Share it with love.

Leave a Reply

Your email address will not be published.