Objects & collections
Object.keys(), values(), entries()
A bridge between objects and arrays: everything arrays can do becomes available to an object.
Why it exists
Arrays have lots of handy tools: for...of, map, filter, reduce, length. A plain object has none of them — you can't even walk it with for...of. These three functions turn an object into an array, and from there you can do everything arrays can. And Object.fromEntries puts the result back into an object.
Where it's used
- Walk every property:
for (const [key, value] of Object.entries(obj)). - Count properties:
Object.keys(obj).length. - Sum the values:
Object.values(cart).reduce(...). - Transform an object:
Object.fromEntries(Object.entries(obj).map(...)).
Syntax
Object.keys(object) // [key, …]
Object.values(object) // [value, …]
Object.entries(object) // [[key, value], …]
Object.fromEntries(pairs) // objectExamples
const prices = { tea: 200, coffee: 300 };
Object.keys(prices); // → ["tea", "coffee"]const scores = { anna: 5, ben: 3 };
Object.values(scores); // → [5, 3]
Object.entries(scores); // → [["anna", 5], ["ben", 3]]const prices = { tea: 200, coffee: 300 };
const doubled = Object.fromEntries(
Object.entries(prices).map(([name, price]) => [name, price * 2]),
);
doubled; // → { tea: 400, coffee: 600 }map for an object: entries → map → fromEntriesObject.keys({}).length === 0; // → trueResults after // → aren't just written down — an automatic check runs and verifies them before every site update.
Why it works this way
All three walk the object's own enumerable properties (inherited ones like toString are left out) and return a new array:
Object.keys— an array of keys (always strings);Object.values— an array of values;Object.entries— an array of pairs, each pair a two-item array[key, value].
The order is the order the properties were added, except that integer-like keys ("1", "2") come first, in ascending order.
Object.fromEntries(pairs) is the reverse: it takes an array of pairs and creates an object from them. Together with entries, it's the standard way to "run an object through map or filter".
Traps
How it differs from…
for...ofloopfor...of can't walk a plain object directly — only the array returned by
keys,valuesorentries.- Objects
{ } How objects themselves work — keys, values, in.
When to pick something else
If you only need to read one or two known properties, access them directly — there's no reason to turn the object into an array. If the data is really a list of similar records, store it as an array, not as an object with numbered keys.