Object.entries(): loop and transform objects (ES2017)
What you’ll learn
Section titled “What you’ll learn”- What
Object.entries()returns and how to destructure each pair. - The
entries→ array methods →Object.fromEntries()pattern for transforming objects, and conversion to and fromMap. - How to build a query string and a changed-fields diff.
- The pitfalls: snapshots, sorting, numeric keys and TypeScript typing.
Summary
Section titled “Summary”TL;DR: Object.entries(obj) returns a new array of [key, value] arrays for the object’s own, enumerable, string-keyed properties, in the same order as Object.keys(). Pair it with for...of and destructuring to loop, or with Object.fromEntries() (ES2019) to build a transformed object.
It was added in ECMAScript 2017, together with Object.values(), and is supported by every current browser and runtime (details in Compatibility).
The problem it solves
Section titled “The problem it solves”Most object loops need both key and value. Before ES2017 you collected the keys and indexed back into the object each time. The invented OrdersPortal app below turns order-search filters into query parameters.
Running the samples: save a sample as a .mjs file and run it with Node.js 22 (node sample.mjs), or paste it into a browser console. All outputs shown were produced with Node.js 22.23.
// OrdersPortal: query filters typed by the user.const filters = { status: 'shipped', carrier: 'UPS', page: 2 };
// Before ES2017: keys plus a lookup per key.const before = Object.keys(filters).map((key) => key + '=' + filters[key]);console.log(before.join('&'));
// ES2017: key and value together, destructured in the loop head.for (const [key, value] of Object.entries(filters)) { console.log(`${key} -> ${value}`);}console.log(Object.entries(filters));Output:
status=shipped&carrier=UPS&page=2status -> shippedcarrier -> UPSpage -> 2[ [ 'status', 'shipped' ], [ 'carrier', 'UPS' ], [ 'page', 2 ] ]How it works
Section titled “How it works”// Fragment: signatureconst entries = Object.entries(obj); // Array<[string, any]>Object.entries() runs ToObject(obj), then EnumerableOwnProperties(obj, key+value), wrapping each pair in a fresh two-element array. It shares the selection and ordering rules of Object.keys() and, like Object.values(), runs getters. What is specific is the pair shape, which other APIs accept as input:
new Map(Object.entries(obj))builds aMap.Object.fromEntries(iterable)(ES2019) is the inverse: it accepts any iterable of pairs, such as aMapor the output of.map().new URLSearchParams(Object.entries(obj))builds a query string.
const prices = { 'A-77': 19.99, 'B-12': 45, 'C-03': 2.5 };
// Transform an object: entries -> array methods -> Object.fromEntries (ES2019).const discounted = Object.fromEntries( Object.entries(prices).map(([sku, price]) => [sku, Math.round(price * 90) / 100]),);console.log(discounted);
const cheap = Object.fromEntries(Object.entries(prices).filter(([, price]) => price < 20));console.log(cheap);
// Object -> Map and back.const map = new Map(Object.entries(prices));console.log(map.get('B-12'), Object.fromEntries(map));
// Entries are snapshots: changing the array does not change the object.const entries = Object.entries(prices);entries[0][1] = 0;console.log(prices['A-77']);
// Sort by value (the object itself keeps insertion order).console.log(Object.entries(prices).sort(([, a], [, b]) => a - b).map(([sku]) => sku));Output:
{ 'A-77': 17.99, 'B-12': 40.5, 'C-03': 2.25 }{ 'A-77': 19.99, 'C-03': 2.5 }45 { 'A-77': 19.99, 'B-12': 45, 'C-03': 2.5 }19.99[ 'C-03', 'A-77', 'B-12' ]The pair arrays are new, but the values in them are the original references: replacing entries[0][1] changes nothing, mutating a stored object would.
TypeScript
Section titled “TypeScript”The typings in lib.es2017.object.d.ts mirror Object.values(): entries<T>(o: { [s: string]: T } | ArrayLike<T>): [string, T][], falling back to [string, any][]. Keys are always string, never keyof T; a Record<string, number> yields [string, number][], an interface yields [string, any][]. Object.fromEntries() (in lib.es2019.object.d.ts) returns { [k: string]: T }, so a transformed object loses its original property names in the type; add an explicit return type when that matters.
Realistic example
Section titled “Realistic example”OrdersPortal needs two helpers: one that turns a filter object into a query string, dropping empty filters and repeating multi-value filters, and one that sends only the fields a user actually changed in an edit form.
// OrdersPortal: build a query string and a diff of changed fields.function toQuery(filters) { const params = new URLSearchParams(); for (const [key, value] of Object.entries(filters)) { if (value === undefined || value === null || value === '') continue; // drop empty filters for (const item of [value].flat()) params.append(key, String(item)); } return params.toString();}
console.log(toQuery({ status: ['paid', 'shipped'], carrier: '', page: 2, q: 'gift card', from: undefined }));
function changedFields(before, after) { return Object.fromEntries( Object.entries(after).filter(([key, value]) => !Object.is(before[key], value)), );}
const saved = { notes: 'Leave at door', giftWrap: false, quantity: 1 };const edited = { notes: 'Leave at door', giftWrap: true, quantity: 2 };console.log(changedFields(saved, edited));Output:
status=paid&status=shipped&page=2&q=gift+card{ giftWrap: true, quantity: 2 }changedFields is deliberately shallow: a rebuilt nested object counts as changed even if equal, and a key removed from after is not reported. Add those rules if the API needs them.
Common mistakes
Section titled “Common mistakes”- Sorting and expecting the object to follow. Sorting entries does not reorder the object, and rebuilding with
Object.fromEntries()cannot reorder integer-like keys such as'1001', which always come first. Keep the sorted array, or use aMap. - Using
Object.entries()on aMap. It returns[]; loop over theMapdirectly. - Forgetting that keys are strings.
Object.entries([5, 6])gives[['0', 5], ['1', 6]]. For arrays,array.entries()yields numeric indexes and includes holes asundefined. - Dropping symbol keys silently. Round-tripping through entries and
fromEntriesloses symbol-keyed and non-enumerable properties, and turns getters into plain values. UseObject.getOwnPropertyDescriptors()for a faithful copy. - Trusting keys from user input. A
['__proto__', {...}]pair makesObject.fromEntries()create an own property named__proto__(it does not change the prototype). That is safe alone, but not when the object later reaches a recursive merge helper. Validate keys against an allow-list.
When to use it and when not to
Section titled “When to use it and when not to”| Task | Best fit |
|---|---|
| Loop over key and value | for (const [k, v] of Object.entries(obj)) |
| Map or filter an object into a new object | Object.fromEntries(Object.entries(obj).map(...)) |
Convert an object to a Map |
new Map(Object.entries(obj)) |
| Only values, for aggregation | Object.values() |
| Only keys, for validation | Object.keys() |
| Copy accessors, symbols and attributes | Object.getOwnPropertyDescriptors() |
Compatibility
Section titled “Compatibility”According to MDN’s browser compatibility data, Object.entries() is supported in Chrome 54, Edge 14, Firefox 47, Safari 10.1 (iOS 10.3), Node.js 7.0, Deno 1.0 and Bun 1.0; Internet Explorer never supported it. Object.fromEntries() (ES2019) is supported in Chrome 73, Edge 79, Firefox 63, Safari 12.1 (iOS 12.2), Node.js 12.0, Deno 1.0 and Bun 1.0. In TypeScript, the lib must include es2017 for entries and es2019 for fromEntries if your project pins an older one.
Interview questions
Section titled “Interview questions”1. How do you map over an object’s values and get an object back?
Object.fromEntries(Object.entries(obj).map(([k, v]) => [k, f(v)])): entries in, array methods, pairs back out.
2. Why doesn’t sorting entries and calling Object.fromEntries() always give a sorted object?
Property order is defined by key type, not by creation alone: integer-like keys are always listed first in ascending order. Only non-index string keys keep insertion order. If ordering is part of the data, keep an array or a Map.
3. Senior scenario: a settings service stores feature flags as an object, and a new requirement adds per-flag metadata and frequent updates from several sources. Would you keep using objects with Object.entries()?
For read-mostly, JSON-shaped config, yes: entries make it easy to validate, diff and serialize. If flags change constantly, keys can be arbitrary strings like __proto__, or you need guaranteed insertion order and cheap size checks, keep a Map<string, Flag> in memory and convert at the edges with new Map(Object.entries(json)) and Object.fromEntries(map). The wire format stays plain JSON; the runtime model avoids prototype and ordering surprises.
Key takeaways
Section titled “Key takeaways”Object.entries()(ES2017) returns[key, value]pairs with the same rules and order asObject.keys().- Destructure pairs in
for...of; transform objects withentries→ array methods →Object.fromEntries()(ES2019). - It is the bridge between objects,
Maps andURLSearchParams. - Entries are a snapshot; sorting them does not reorder the object, and integer-like keys always come first.
Related pages
Section titled “Related pages”- Object.keys(): the shared enumeration and ordering rules.
- Object.values(): values only, for aggregation.
- Object.getOwnPropertyDescriptors(): copy properties faithfully.
- Destructuring, for…of and Map and Set
- JavaScript interview questions
Official references
Section titled “Official references”- ECMAScript Language Specification,
Object.entries ( O )(current draft; first published in ECMAScript 2017) - ECMAScript Language Specification,
Object.fromEntries ( iterable )(first published in ECMAScript 2019) - TC39 proposal: Object.values / Object.entries
- MDN: Object.entries()
- MDN: Object.fromEntries()
- TypeScript 6.0.3:
lib.es2017.object.d.ts