The Object.fromEntries() method creates an object from a list of key-value pairs.
Example
fromEntries() Syntax
The syntax of the fromEntries() method is:
Object.fromEntries(iterable)
Here, fromEntries() is a static method. Hence, we need to access the method using the class name, Object.
fromEntries() Parameters
The fromEntries() method takes in:
- iterable - an iterable such as an
Arrayor aMapor any other object implementing the iterable protocol.
fromEntries() Return Value
The fromEntries() method returns:
- a new object whose properties are given by the entries of the iterable.
Note: Object.fromEntries() performs the reverse function of Object.entries().
Example: JavaScript Object.fromEntries()
Output
{ firstName: 'John', lastName: 'Doe' }
{ '0': 'x', '1': 'y', '2': 'z' }
In the above example, we have first created the entries array, which consists of two key-value pairs: ["firstName", "John"] and ["lastName", "Doe"].
We then used the Object.fromEntries() method to convert the entries array into an object possessing the key-value pairs specified in the array.
const obj = Object.fromEntries(entries);
The output indicates that the arrays have been converted to their respective objects.
Then, we repeated the same process with the arr array.
Recommended Reading: