JavaScript Object.fromEntries(): Creating Objects from Entries
The Object.fromEntries()
method in JavaScript provides a convenient way to transform a list of key-value pairs into an object. This method is particularly useful when you have data in a format like an array of arrays or a Map and need to convert it into a standard JavaScript object. This comprehensive guide will walk you through the syntax, usage, and practical examples of Object.fromEntries()
.
What is Object.fromEntries()?
Object.fromEntries()
is a static method that takes an iterable (like an array or a Map) of key-value pairs and returns a new object. Each key-value pair in the iterable becomes a property in the resulting object.
Purpose of Object.fromEntries()
The primary purpose of Object.fromEntries()
is to simplify the process of creating objects from data structures that store key-value pairs. It allows you to convert data from formats like arrays of arrays or Maps into standard JavaScript objects, making the data more accessible and easier to work with.
Syntax
The syntax for Object.fromEntries()
is straightforward:
Object.fromEntries(iterable);
iterable
: An iterable object such as an Array or Map that contains key-value pairs. Each key-value pair is expected to be an array of two elements, where the first element is the key and the second element is the value.
Usage
Converting an Array of Arrays to an Object
One common use case for Object.fromEntries()
is converting an array of arrays into an object. Each inner array represents a key-value pair.
const entriesArray = [
["name", "John"],
["age", 30],
["city", "New York"],
];
const objFromArray = Object.fromEntries(entriesArray);
console.log(objFromArray);
// Output: { name: 'John', age: 30, city: 'New York' }
Converting a Map to an Object
Another common use case is converting a Map object to a standard JavaScript object.
const entriesMap = new Map([
["name", "Alice"],
["age", 25],
["country", "Canada"],
]);
const objFromMap = Object.fromEntries(entriesMap);
console.log(objFromMap);
// Output: { name: 'Alice', age: 25, country: 'Canada' }
Creating Objects from Dynamic Data
Object.fromEntries()
can also be used with dynamically generated data, such as data fetched from an API or computed based on user input.
const keys = ["firstName", "lastName", "email"];
const values = ["Bob", "Smith", "[email protected]"];
const dynamicEntries = keys.map((key, index) => [key, values[index]]);
const objFromDynamic = Object.fromEntries(dynamicEntries);
console.log(objFromDynamic);
// Output: { firstName: 'Bob', lastName: 'Smith', email: '[email protected]' }
Practical Examples
Example 1: Creating an Object from URL Parameters
Consider a scenario where you want to extract URL parameters and convert them into an object.
const urlParams = new URLSearchParams("name=Charlie&age=35&occupation=Engineer");
const paramsObj = Object.fromEntries(urlParams);
console.log(paramsObj);
// Output: { name: 'Charlie', age: '35', occupation: 'Engineer' }
Example 2: Transforming Data from an API Response
Suppose you have an API that returns an array of key-value pairs, and you want to convert it into an object for easier access.
const apiResponse = [
{ key: "productName", value: "Laptop" },
{ key: "price", value: 1200 },
{ key: "category", value: "Electronics" },
];
const transformedEntries = apiResponse.map((item) => [item.key, item.value]);
const productObj = Object.fromEntries(transformedEntries);
console.log(productObj);
// Output: { productName: 'Laptop', price: 1200, category: 'Electronics' }
Example 3: Creating an Object from Form Data
When handling form submissions, you might need to convert the form data into an object.
<form id="myForm">
<input type="text" name="username" value="David" />
<input type="email" name="email" value="[email protected]" />
<input type="text" name="city" value="Los Angeles" />
</form>
<script>
const form = document.getElementById("myForm");
form.addEventListener("submit", function (event) {
event.preventDefault(); // Prevent the default form submission
const formData = new FormData(form);
const formEntries = Array.from(formData.entries());
const formObj = Object.fromEntries(formEntries);
console.log(formObj);
// Output: { username: 'David', email: '[email protected]', city: 'Los Angeles' }
});
</script>
Example 4: Creating a Frequency Counter Object from an Array
You can use Object.fromEntries
to efficiently create a frequency counter object from an array of elements.
const arr = ["apple", "banana", "apple", "orange", "banana", "apple"];
const frequencyMap = arr.reduce((map, element) => {
map.set(element, (map.get(element) || 0) + 1);
return map;
}, new Map());
const frequencyObj = Object.fromEntries(frequencyMap);
console.log(frequencyObj);
// Output: { apple: 3, banana: 2, orange: 1 }
Example 5: Creating a Deep Object from Nested Entries
Suppose you have a nested array of entries representing a complex object structure. You can use recursion with Object.fromEntries
to create a deep object.
function deepFromEntries(entries) {
if (!Array.isArray(entries)) {
return entries;
}
return Object.fromEntries(
entries.map(([key, value]) => [key, Array.isArray(value) ? deepFromEntries(value) : value])
);
}
const nestedEntries = [
["name", "Eve"],
["address", [["street", "123 Main St"], ["city", "San Francisco"]]],
];
const deepObj = deepFromEntries(nestedEntries);
console.log(deepObj);
// Output: { name: 'Eve', address: { street: '123 Main St', city: 'San Francisco' } }
Notes
- The
Object.fromEntries()
method expects each element in the iterable to be an array with exactly two elements: the key and the value. If an element does not conform to this structure, it may lead to unexpected results or errors. - Keys in the resulting object are strings. If a non-string key is provided in the input iterable, it will be converted to a string.
Object.fromEntries()
is the inverse ofObject.entries()
. WhileObject.entries()
converts an object into an array of key-value pairs,Object.fromEntries()
converts an array of key-value pairs back into an object.
Browser Support
The Object.fromEntries()
method is supported by all modern browsers.
| Browser | Version |
| ————– | ——- |
| Chrome | 73+ |
| Firefox | 63+ |
| Safari | 12.1+ |
| Edge | 79+ |
| Opera | 60+ |
| Internet Explorer | Not Supported |
Conclusion
The Object.fromEntries()
method is a valuable tool for converting various data structures into JavaScript objects. Its simplicity and versatility make it an excellent addition to your JavaScript toolkit, especially when dealing with data transformations and dynamic object creation. By understanding its syntax and practical applications, you can write cleaner and more efficient code.