Object.fromEntries()
Static method that converts an iterable of [key, value] pairs into a plain object. The inverse of Object.entries().
When to use it
- FormData to object —
Object.fromEntries(new FormData(form)) - Map to object —
Object.fromEntries(map) - Transforming objects — entries → map/filter → back to object
- URL params to object —
Object.fromEntries(new URLSearchParams(...))
Anatomy
// from an array of pairs
Object.fromEntries([['a', 1], ['b', 2]])
// { a: 1, b: 2 }
// from a Map
const map = new Map([['x', 10], ['y', 20]])
Object.fromEntries(map)
// { x: 10, y: 20 }
// from FormData
Object.fromEntries(new FormData(form))
// { name: '...', email: '...' }
// from URLSearchParams
Object.fromEntries(new URLSearchParams('?page=1&sort=name'))
// { page: '1', sort: 'name' }At a glance
| Input type | What you get |
|---|---|
[['key', 'value'], ...] | Plain object from array of pairs |
Map | Plain object from Map entries |
FormData | Plain object from form fields |
URLSearchParams | Plain object from query string |
1. Simple — array of pairs to object
const pairs = [['name', 'Alice'], ['role', 'admin']]
const obj = Object.fromEntries(pairs)
// { name: 'Alice', role: 'admin' }2. Intermediate — transform an object
const prices = { apple: 1.2, banana: 0.5, cherry: 2.0 }
// uppercase all keys
const upper = Object.fromEntries(
Object.entries(prices).map(([key, val]) => [key.toUpperCase(), val])
)
// { APPLE: 1.2, BANANA: 0.5, CHERRY: 2 }
// filter out cheap items
const premium = Object.fromEntries(
Object.entries(prices).filter(([, val]) => val > 1)
)
// { apple: 1.2, cherry: 2 }3. Advanced — query string round-trip
// parse a query string into an object
const params = new URLSearchParams('?page=2&sort=name&order=asc')
const obj = Object.fromEntries(params)
// { page: '2', sort: 'name', order: 'asc' }
// modify and serialize back
obj.page = '3'
const qs = new URLSearchParams(obj).toString()
// 'page=3&sort=name&order=asc'Gotchas
Duplicate keys — last one wins
Object.fromEntries([['a', 1], ['a', 2]])
// { a: 2 } — the second pair overwrites the first
// same issue with FormData checkboxes — use .getAll() insteadAll values become the value type — no coercion
const params = new URLSearchParams('?count=5&active=true')
const obj = Object.fromEntries(params)
obj.count // '5' — string, not number
obj.active // 'true' — string, not boolean
// parse manually if you need typed valuesRelated
Last updated on