The fromEntries
function is defined in the Object
class in JS. The fromEntries
function converts an iterable object to a JS object.
Object.fromEntries(iterable);
iterable
is an object that implements the iterable protocol such as Array
or Map
.Object
that contains the key-value pairs returned by the passed iterable
.The fromEntries
function takes an iterable
object and converts it into a JS Object
. iterable
is an object that can produce an iterator
object. An iterator is a 2 element array, where the first index element represents the key and the second index element represents the value.
The following code converts an Array
to an Object
.
let arr = [['0', 'S'], ['1', 'H'], ['2', 'O'], ['3', 'T']];let obj = Object.fromEntries(arr);console.log('Array:', arr);console.log('Object:', obj);
Array: [['0', 'S'], ['1', 'H'], ['2', 'O'], ['3', 'T']]
Object: {0: 'S', 1: 'H', 2: 'O', 3: 'T'}
In the example above, the arr
variable contains an Array
that has four 2 element arrays that represent an iterator
. The Object.fromEntries
function converts the arr
to an Object
. The first element of all the arrays inside arr
become the key of obj
, and the second element of all the arrays inside arr
become the respective values of obj
.
Free Resources