Understanding Object.fromEntries()

Understanding Object.fromEntries()

A quick guide to understanding `Object.fromEntries()`

The Object.fromEntries() method transforms an iterable like Map or Array to an object. In simple words, It converts your list into an object.

let's take a look at the syntax.

Object.fromEntries(iterable);

๐Ÿ‘‰ Here are some of the major points you have to remember while using Object.fromEntries()

  1. The Object.fromEntries() method takes a list(iterable) of key-value pairs and returns a new object whose properties are given by those entries.

  2. The iterable must follow the shape structure of a 2D array. The first index of the nested list will become the key and the second index will become the value. See the example for more clarification of this point.

  3. Object.fromEntries() performs the reverse of Object.entries().

Examples:

๐Ÿ‘‰ Conversion of Map iterable

const userEntries = new Map([
  ['username', 'Jhone'],
  ['age', 42],
]);

const user = Object.fromEntries(userEntries);
console.log(user); // { username: "Jhone", age: 42 }

๐Ÿ‘‰ Conversion of Array Iterable

const userEntries = [ 
  ['username', 'Jhone'], 
  ['age', 42], 
  ['isActive', false] 
];

const user = Object.fromEntries(userEntries);
console.log(obj); // { username: "Jhone", age: 42, isActive: false }

That's it, folks! hope it was a good read for you. Thank you! โœจ

๐Ÿ‘‰ References:

The official documentation of Object.fromEntries()

๐Ÿ‘‰ Follow me: Github Twitter LinkedIn Youtube

ย