How Object.fromEntries Works in JavaScript

JavaScript’s Object.fromEntries() method provides a built-in way to transform a list of key-value pairs into a standard object. Introduced in ECMAScript 2019 (ES10), this method acts as the direct inverse of Object.entries(). This article explains how Object.fromEntries() reconstructs objects, explores its syntax and behavior, and demonstrates common use cases such as object transformations, converting Maps, and parsing query parameters.

Syntax and Basic Mechanics

The Object.fromEntries() method accepts a single argument: an iterable containing entries formatted as two-element arrays [key, value].

Object.fromEntries(iterable);

When called, the method iterates over the provided data structure, extracting the first element of each pair as the object property key and the second element as the property value.

const entries = [
  ['name', 'Alice'],
  ['role', 'Developer'],
  ['active', true]
];

const user = Object.fromEntries(entries);

console.log(user);
// Output: { name: 'Alice', role: 'Developer', active: true }

Common Use Cases

1. Transforming Objects with Array Methods

Standard JavaScript objects do not have native array methods like .map(), .filter(), or .reduce(). By pairing Object.entries() with Object.fromEntries(), you can apply array methods to an object and convert it back into an object seamlessly.

const inventory = {
  apples: 10,
  bananas: 5,
  oranges: 8
};

// Double the quantity of each fruit
const doubledInventory = Object.fromEntries(
  Object.entries(inventory).map(([fruit, count]) => [fruit, count * 2])
);

console.log(doubledInventory);
// Output: { apples: 20, bananas: 10, oranges: 16 }

2. Converting a Map to an Object

The native JavaScript Map structure is already an iterable of key-value pairs. Object.fromEntries() converts a Map directly into a plain object without requiring manual loops.

const map = new Map([
  ['id', 101],
  ['status', 'success']
]);

const obj = Object.fromEntries(map);

console.log(obj);
// Output: { id: 101, status: 'success' }

3. Parsing URL Query Strings

The URLSearchParams API is an iterable collection of key-value pairs representing URL query parameters. You can quickly parse these parameters into an object using Object.fromEntries().

const queryString = '?search=javascript&page=2&sort=desc';
const urlParams = new URLSearchParams(queryString);

const paramsObject = Object.fromEntries(urlParams);

console.log(paramsObject);
// Output: { search: 'javascript', page: '2', sort: 'desc' }

Important Behavior to Keep in Mind