DEV Community

Sourav
Sourav

Posted on

1

How to Convert Iterables to Objects Using Object.fromEntries() in JavaScript

In JavaScript, managing key-value pairs is a frequent task. The Object.fromEntries() method, introduced in ECMAScript 2019, simplifies this by allowing you to easily convert an iterable (such as an array or a Map) into a plain object. This function is incredibly helpful when dealing with Map objects or transforming data structures that hold key-value pairs.

Syntax and Usage:
The syntax of the Object.fromEntries() method is straightforward:
`Object.fromEntries(iterable);

Example
const entries = [['name', 'John'], ['age', 30], ['city', 'New York']];
const obj = Object.fromEntries(entries);
console.log(obj);

Output


{ name: 'John', age: 30, city: 'New York' }

In this example, the Object.fromEntries() method converts an array of arrays (each containing a key-value pair) into an object.

Practical Applications:
Converting Maps to Objects: If you have a Map object and want to convert it into a plain object, Object.fromEntries() provides an easy solution.

const map = new Map([
['name', 'Alice'],
['age', 25]
]);

const userObj = Object.fromEntries(map);
console.log(userObj); // { name: 'Alice', age: 25 }
Filtering Key-Value Pairs: You can also use Object.fromEntries() in combination with other array methods to filter and modify key-value pairs before converting them into an object.

const data = [
['name', 'Alice'],
['age', 25],
['city', 'Paris']
];

const filteredData = Object.fromEntries(
data.filter(([key, value]) => key !== 'age')
);

console.log(filteredData); // { name: 'Alice', city: 'Paris' }
Performance Considerations:
Object.fromEntries() works well for typical use cases, such as converting a Map or an array of key-value pairs into an object. However, when dealing with extremely large datasets, performance might become a concern. In these cases, it is recommended to test and optimize your code for specific requirements.

Compatibility and Browser Support:
The Object.fromEntries() method is supported by the following browsers and environments:

Chrome 73+
Firefox 68+
Safari 12.1+
Node.js 12+
If you're targeting older browsers, consider using a polyfill to ensure compatibility.

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

The best way to debug slow web pages cover image

The best way to debug slow web pages

Tools like Page Speed Insights and Google Lighthouse are great for providing advice for front end performance issues. But what these tools can’t do, is evaluate performance across your entire stack of distributed services and applications.

Watch video