Home >Web Front-end >JS Tutorial >How to Convert Iterables to Objects Using Object.fromEntries() in JavaScript
Key-value pairs are often processed in JavaScript development. The Object.fromEntries()
method introduced in ECMAScript 2019 simplifies this process, allowing you to easily convert iterable objects (such as arrays or Maps) into ordinary objects. This method is useful when working with Map objects or transforming data structures containing key-value pairs.
Grammar and usage:
Object.fromEntries()
The syntax of the method is simple:
Object.fromEntries(iterable);
Example:
<code class="language-javascript">const entries = [['name', 'John'], ['age', 30], ['city', 'New York']]; const obj = Object.fromEntries(entries); console.log(obj); // 输出: { name: 'John', age: 30, city: 'New York' }</code>
In this example, the Object.fromEntries()
method converts a two-dimensional array containing key-value pairs into an object.
Practical application:
Object.fromEntries()
provides a simple solution. <code class="language-javascript">const map = new Map([ ['name', 'Alice'], ['age', 25] ]); const userObj = Object.fromEntries(map); console.log(userObj); // { name: 'Alice', age: 25 }</code>
Object.fromEntries()
in conjunction with other array methods to filter and modify key-value pairs before converting them to objects. <code class="language-javascript">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' }</code>
Performance considerations:
Object.fromEntries()
is suitable for typical use cases, such as converting a Map or an array of key-value pairs to an object. However, performance can become an issue when dealing with very large data sets. In this case, it is recommended to test and optimize the code according to specific needs.
Compatibility and browser support:
Object.fromEntries()
method is supported by the following browsers and environments:
If you need compatibility with older browsers, please consider using a polyfill to ensure compatibility.
The above is the detailed content of How to Convert Iterables to Objects Using Object.fromEntries() in JavaScript. For more information, please follow other related articles on the PHP Chinese website!