Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

javascript
array
object
iterator

What is Object.fromEntries() in Javascript?

Hammad Nasir

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Overview

The fromEntries function is defined in the Object class in JS. The fromEntries function converts an iterable object to a JS object.

Syntax

Object.fromEntries(iterable);

Parameters

  • iterable is an object that implements the iterable protocol such as Array or Map.

Return value

  • A JS Object that contains the key-value pairs returned by the passed iterable.

Description

The fromEntries function takes an iterable object and converts it into a JS Object. iterable is an object that can produce an iterator object. An iterator is a 2 element array, where the first index element represents the key and the second index element represents the value.

Example

The following code converts an Array to an Object.

let arr = [['0', 'S'], ['1', 'H'], ['2', 'O'], ['3', 'T']];
let obj = Object.fromEntries(arr);
console.log('Array:', arr);
console.log('Object:', obj);

Output

Array: [['0', 'S'], ['1', 'H'], ['2', 'O'], ['3', 'T']]
Object: {0: 'S', 1: 'H', 2: 'O', 3: 'T'}

In the example above, the arr variable contains an Array that has four 2 element arrays that represent an iterator. The Object.fromEntries function converts the arr to an Object. The first element of all the arrays inside arr become the key of obj, and the second element of all the arrays inside arr become the respective values of obj.

RELATED TAGS

javascript
array
object
iterator

CONTRIBUTOR

Hammad Nasir
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring