JavaScriptEasy
Convert an object to an array of pairs
Object.entries(obj) returns an array of [key, value] pairs for the object's own enumerable string-keyed properties, in property order; use Reflect.ownKeys if you also need symbol or non-enumerable keys.
Related methods
Object.keys(obj): only keys.Object.values(obj): only values.Object.entries(obj): pairs.Map.prototype.entries()/[...map]: pairs from a Map. All of them include only own enumerable string keys, never inherited ones.
Property order
Integer-like keys come first in ascending numeric order, then string keys in insertion order, then (for Reflect.ownKeys) symbols. This surprises people when keys look like numbers: { b: 1, 2: "x", a: 2, 1: "y" } lists 1 and 2 first.
Typical uses
- Iterating with destructuring:
for (const [key, value] of Object.entries(obj)). - Sorting an object by its values (objects themselves cannot be sorted).
- Converting to a
Map:new Map(Object.entries(obj)). - Transforming and rebuilding with
Object.fromEntries. - Filtering out empty or sensitive fields before sending data.
Deep version
For nested objects, flatten into path/value pairs ("user.address.city"), which is useful for forms, query strings and diffing (see "Flatten a nested object").
Code example
js
1const user = { name: "Ada", age: 36, 2: "two", 1: "one", [Symbol("id")]: 7 };2Object.defineProperty(user, "secret", { value: "hidden", enumerable: false });34console.log(Object.entries(user)); // [["1", "one"], ["2", "two"], ["name", "Ada"], ["age", 36]] - integer keys first5console.log(Reflect.ownKeys(user)); // ["1", "2", "name", "age", "secret", Symbol(id)]67// Iterate with destructuring8for (const [key, value] of Object.entries({ theme: "dark", fontSize: 16 })) console.log(`${key} = ${value}`);910// Sort an object by its values11const scores = { ada: 88, linus: 95, grace: 91 };12const ranked = Object.entries(scores).sort(([, a], [, b]) => b - a);13console.log(ranked.map(([name]) => name)); // ["linus", "grace", "ada"]1415// Filter fields, then rebuild16const form = { email: "ada@example.com", password: "hunter2", nickname: "", age: 36 };17const safe = Object.fromEntries(Object.entries(form).filter(([k, v]) => k !== "password" && v !== ""));18console.log(safe); // { email: "ada@example.com", age: 36 }1920// Object -> Map21const map = new Map(Object.entries(scores));22console.log(map.get("grace"), map.size); // 91 32324// Deep: nested object -> path/value pairs25const toPairsDeep = (obj, prefix = "") =>26 Object.entries(obj).flatMap(([k, v]) =>27 v && typeof v === "object" && !Array.isArray(v) ? toPairsDeep(v, `${prefix}${k}.`) : [[`${prefix}${k}`, v]]28 );29console.log(toPairsDeep({ user: { name: "Ada", address: { city: "London" } }, active: true }));30// [["user.name", "Ada"], ["user.address.city", "London"], ["active", true]]
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.