How to Use Object.fromEntries in JavaScript: Syntax and Examples
Object.fromEntries converts an array of key-value pairs into an object. It takes an iterable like an array of arrays and returns a new object with those keys and values.Syntax
The Object.fromEntries() method takes one argument: an iterable of key-value pairs (usually an array of arrays). It returns a new object constructed from these pairs.
iterable: An array or any iterable where each item is a two-element array: [key, value].- Returns: A new object with keys and values from the iterable.
javascript
const obj = Object.fromEntries(iterable);
Example
This example shows how to convert an array of key-value pairs into an object using Object.fromEntries. It creates an object with properties from the array.
javascript
const entries = [['name', 'Alice'], ['age', 30], ['city', 'Paris']]; const obj = Object.fromEntries(entries); console.log(obj);
Output
{"name":"Alice","age":30,"city":"Paris"}
Common Pitfalls
Common mistakes include passing a non-iterable or an iterable with items that are not two-element arrays. Also, keys must be strings or symbols; other types will be converted to strings.
Wrong usage example:
const wrong = Object.fromEntries(["name", "Alice"]); // Throws error
Correct usage:
const correct = Object.fromEntries([['name', 'Alice']]);
Quick Reference
| Feature | Description |
|---|---|
| Input | Iterable of [key, value] pairs (e.g., array of arrays) |
| Output | New object with keys and values from input |
| Key Types | Strings or symbols (others converted to strings) |
| Throws Error | If input is not iterable or pairs are not length 2 |
| Use Case | Convert Map or array of pairs to object |
Key Takeaways
Object.fromEntries converts arrays of key-value pairs into objects.
Input must be an iterable of two-element arrays representing [key, value].
Keys are converted to strings if they are not strings or symbols.
Passing invalid input causes errors, so ensure correct structure.
Useful to transform Maps or arrays back into plain objects.