Summary: in this tutorial, you will learn how to use the JavaScript Object.fromEntries()
method to transform a list of key-value pairs into an object.
ES6 introduces the Object.entries()
method that allows you to transform an object into an array:
const boxStyle = {
color: 'red',
borderWidth: '1px'
};
let arr = Object.entries(boxStyle);
console.log(arr);
Code language: JavaScript (javascript)
Output:
[['color', 'red'],['borderWidth', '1px']]
Code language: JSON / JSON with Comments (json)
But what if you wanted to do the opposite and convert a list of key-value pairs into an object?
ES2019 introduced the Object.fromEntries()
method that allows you to easily convert a list of key-value pairs into an object.
let arr = [['color', 'red'],['borderWidth', '1px']];
let obj = Object.fromEntries(arr);
Code language: JavaScript (javascript)
Output:
{color: "red", borderWidth: "1px"}
Code language: CSS (css)
Introduction to JavaScript Object.fromEntries() method
The Object.fromEntries()
accepts an iterable such as Array
or Map
and transforms it into an Object:
Object.fromEntries(iterable);
Code language: JavaScript (javascript)
The Object.fromEntries()
returns a new object whose properties are specified by the entries of the iterable.
The Object.fromEntries()
expects the iterable to return an iterator object that produces key-value pairs. It uses the key as the property key of the object and value as the value associated with the property key.
The Object.fromEntries()
performs the reverse of Object.entries()
.
JavaScript Object.fromEntries() examples
Let’s take some examples of using the Object.fromEntries()
method.
1) Converting an Array to an Object
This example shows how to convert an array into an object:
const arr = [
['firstName', 'John'],
['lastName', 'Doe'],
['age', 20]
];
const person = Object.fromEntries(arr);
console.log(person);
Code language: JavaScript (javascript)
Output:
{firstName: "John", lastName: "Doe", age: 20}
Code language: CSS (css)
2) Converting a Map to an Object
The following example shows how to use the Object.fromEntries()
method to convert a Map to an Object:
const config = new Map();
config.set('type', 'database');
config.set('duration', 30);
const cache = Object.fromEntries(config);
console.log(cache);
Code language: JavaScript (javascript)
Output:
{type: "database", duration: 30}
Code language: CSS (css)
3) Converting a URL parameter string into an object
The following example shows how to use the Object.fromEntries()
to convert a query string of a URL to an object whose each property is a parameter:
const params = 'type=listing&page=2&rowCount=10';
const searchParams = new URLSearchParams(params);
console.log(Object.fromEntries(searchParams));
Code language: JavaScript (javascript)
Output:
{type: "listing", page: "2", rowCount: "10"}
Code language: CSS (css)
Summary
- The
Object.fromEntries()
transform an iterable into an object. - The
Object.fromEntries()
performs the reverse ofObject.entries()
.