In this post, Learn Object fromEntries method and example usecases.

ES10 Object fromEntries method

ES10 was introduced fromEntries method in Object API. It is used to convert a list of keys and values into an object.

The object has an existing entries method introduced in ES7 , which converts object keys and values into an array. Object.fromEntries is the reverse of entries API

Object.entries method For example, convert the object to an array

const myobject = { id: 42, name:"franc" };
const myarray = Object.entries(myobject);
console.log(myarray); //[ [ 'id', 42 ], [ 'name', 'franc' ] ]

entries method returns an array, where elements contain keys and values for each key and value pair of an object

Convert Array to Object using fromEntries method

As there is no method to transfer the array returned from entries to an object. Es10 introduced this feature to transfer back to object

const myarray= [ [ 'id', 42 ], [ 'name', 'franc' ] ]
const object = Object.fromEntries(myarray);

Convert Map to Object using fromEntries method

It is easy to convert the map to an object using Object.fromEntries without this, We have to use for loop and create an object using initializing the data

const mapData = new Map([
  ['1', 'franc'],
  ['2', 'john'],
  ['3', 'Andrew']
const myobject = Object.fromEntries(mapData);
console.log(myobject); //{ 1: 'franc', 2: 'john', 3: 'Andrew' }

Here is an example

let str1=" firstString";
let str2="secondString ";

str1.length // outputs 13
str1.trimStart(); // outputs firstString without space
str1.length // outputs 12

str2.length // outputs 13
str2.trimEnd(); // outputs secondString without space
str2.length // outputs 12