The Object.fromEntries()
method creates an object from a list of key-value pairs.
Example
const arr = [
["0", "a"],
["1", "b"],
["2", "c"],
];
// convert the above array into an object
const newObj = Object.fromEntries(arr);
console.log(newObj);
// Output: { '0': 'a', '1': 'b', '2': 'c' }
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
Array
or aMap
or 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()
const entries = [ ["firstName", "John"],
["lastName", "Doe"]
];
// convert the above array into an object
const obj = Object.fromEntries(entries);
console.log(obj);
const arr = [
["0", "x"],
["1", "y"],
["2", "z"],
];
// convert the above array into object
const newObj = Object.fromEntries(arr);
console.log(newObj);
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: