JavaScriptObjects and classes
Object. fromEntries()
Creates an object from a list of [key, value] pairs.
- Returns
- A new object.
- Changes the original
- No
Example
#JavaScript
const pairs = [['html', 11], ['css', 9]]
console.log(Object.fromEntries(pairs))
const prices = { html: 49, css: 59 }
const withTax = Object.fromEntries(
Object.entries(prices).map(([key, price]) => [key, price * 2])
)
console.log(withTax)Console
{ html: 11, css: 9 }
{ html: 98, css: 118 }
Definition and usage
#The Object.fromEntries() method does the opposite of Object.entries(): it builds a plain object from a list of [key, value] pairs. It accepts an array of pairs, a Map, or any iterable object that yields pairs.
It’s most often used to transform objects: you break an object into pairs, change them with array methods, and assemble it back.
It’s also handy for turning a Map into an object, for example before saving data as JSON, and for reading form fields: Object.fromEntries(new FormData(form)).
Syntax
#Syntax
Object.fromEntries(iterable)Parameters
#iterable
list of pairs
An array, a Map, or another iterable object with[key, value]pairs.
Browser support
#Widely available
Works in all modern browsers, phones included. You can use it without worry.
- Chrome
- Edge
- Firefox
- Safari
Good practices
#- You can collect form values in one line:
Object.fromEntries(new FormData(form)). - When keys repeat, the last pair wins.
Related entries
#Spotted a mistake or missing an example? Write to us.