The Object.fromEntries()
method transforms an iterable like Map
or Array
to an object. In simple words, It converts your list into an object.
let's take a look at the syntax.
Object.fromEntries(iterable);
๐ Here are some of the major points you have to remember while using Object.fromEntries()
The Object.fromEntries() method takes a list(iterable) of key-value pairs and returns a new object whose properties are given by those entries.
The iterable must follow the shape structure of a 2D array. The first index of the nested list will become the key and the second index will become the value. See the example for more clarification of this point.
Object.fromEntries()
performs the reverse ofObject.entries()
.
Examples:
๐ Conversion of Map
iterable
const userEntries = new Map([
['username', 'Jhone'],
['age', 42],
]);
const user = Object.fromEntries(userEntries);
console.log(user); // { username: "Jhone", age: 42 }
๐ Conversion of Array
Iterable
const userEntries = [
['username', 'Jhone'],
['age', 42],
['isActive', false]
];
const user = Object.fromEntries(userEntries);
console.log(obj); // { username: "Jhone", age: 42, isActive: false }
That's it, folks! hope it was a good read for you. Thank you! โจ
๐ References:
The official documentation of Object.fromEntries()