JavaScript(JS) object method - fromEntries
In JavaScript, the Object.fromEntries()
method is a static method that creates a new object from an array of key-value pairs. This method takes an iterable object, such as an array, and returns a new object with properties corresponding to the key-value pairs in the iterable.
The syntax for using Object.fromEntries()
is as follows:
Object.fromEntries(iterable)
Where iterable
is an iterable object, such as an array of key-value pairs.
Here's an example of using Object.fromEntries()
:
const entries = [ ['name', 'John'], ['age', 30], ['city', 'New York'] ]; const person = Object.fromEntries(entries); console.log(person); // Output: { name: "John", age: 30, city: "New York" }
In this example, we create an array called entries
that contains three key-value pairs. We then call Object.fromEntries()
on the entries
array to create a new object called person
. The resulting person
object has properties corresponding to the key-value pairs in the entries
array.
It's important to note that Object.fromEntries()
only works with iterable objects that contain key-value pairs, such as arrays of arrays or maps. If you pass in an object that doesn't contain key-value pairs, Object.fromEntries()
will throw a TypeError. Also, if the iterable contains duplicate keys, the last value for each key will be used in the resulting object.