How to use Object.fromEntries in JavaScript?
Object.fromEntries
This method is used to convert an array of key-value pairs into an object.
- The
fromEntriesmethod takes an .argument which is an iterable object such as an array, Map, or object that implements the iterable protocol - The
fromEntriesmethod returns a new object created from the iterable object passed as an argument.
Creating an Object from an array
Creating an Object from Map
Tip: Shallow clone an Object
We can use fromEntries to clone an object. To do this, you need to convert the object to entries and create the object using fromEntries.
Make sure that only the key-value pair is passed; otherwise, there will be an error.
The below code will throw an error
// TypeError will be thrown in all the below case
Object.fromEntries(undefined)
Object.fromEntries(null)
Object.fromEntries(true)
Object.fromEntries(100)
Object.fromEntries("hi")
Object.fromEntries({key: "value"})
Object.fromEntries([1,2,3])