Iterating over objects: Object.keys and Object.entries
Go through every property of an object without naming one: its names with Object.keys, its values with Object.values, and both with Object.entries, taken apart in a loop. See why TypeScript calls each name a string and each value any, and why a name from Object.keys cannot look a value up.
TypeScript
Fundamentals
Iterating over objects: `Object.keys` and `Object.entries`. Read this lesson at .
Tested with TypeScript 7.x · Node.js LTS
At the post office, the clerk reads your parcel's label aloud from top
to bottom: to, Ana; weight, 2 kilograms; fragile, yes. She does not
need to know in advance which lines your label has. She reads every
line's name, then what is written next to it, until the label ends.
So far you have read a task by naming its properties: task.id (id is
short for identifier, the task's number), task.title, task.due.
A property you do not name is never shown, and a new property means a
new line of code. In this lesson you go through an object the way the
clerk reads the label: every property, one after another, without
writing a single name. By the end you can print every property of any
task, and you know what TypeScript can and cannot tell you about the
names and values you get.
Every name, as a list: Object.keys
Object, with a capital O, is a name that comes with the
language, the way console and Math do. Its methods work on any
object. Two of them go through an object's properties for you:
Object.keys gives back the names, and Object.entries gives
back each name together with its value. A property's name is also
called its key, which is where Object.keys gets its name.
Both give back a new list, so you can loop over it, count it, or
print it like any other list. Here is what each gives for lesson
6.8's rent:
names
[ 'id', 'title', 'due' ]
Object.keys(rent)
Does: A list of the names, as text, in the order they were written
It prints [ 'id', 'title', 'due' ], then [ 'id', 'title' ].
water leaves its optional due out, so it has two properties,
and Object.keys
lists only what the object really has. Task says a duemay
be there; the list says whether it is.
Names with their values: Object.entries
A name alone is rarely enough: to print a task's details you need each
value too. Object.entries gives both, as a list of pairs. Each pair
is an entry: the name first, the value second. An entry is a
tuple, lesson 4.6's list with a fixed number of places and a type for
each place.
Lesson 6.8 took a tuple apart with square brackets, and a loop's box
too. Put the two together: in a for...of loop, [key, value] fills
two boxes from each pair by place. Press Next step to follow one
turn of the loop, or let it play:
1
rent
An object with three properties: id, title and due.
2
Object.entries(rent)
A new list of three pairs, one per property, ["id", 1] first.
3
for...of
Takes the pairs one at a time, as it takes the items of any list.
4
[key, value]
Takes the pair apart by place: key is "id", value is 1.
5
console.log
Prints id: 1, and the loop comes back for the next pair.
Object.entries makes a list of pairs; the loop takes each
pair apart by place
All 5 steps shown.Step 1 of 5: rentStep 2 of 5: Object.entries(rent)Step 3 of 5: for...ofStep 4 of 5: [key, value]Step 5 of 5: console.log
All 5 steps shown.
Press Step to watch a new key and value made on every turn:
It prints id: 1, title: Pay rent and due: Monday, one line per
property. The loop never names a property, so it works for any task:
write water in place of rent, and it prints two lines. One more
property, one more line, without a change to the loop.
When the names do not matter, Object.values(rent) gives the values
alone, as a list: [ 1, 'Pay rent', 'Monday' ]. Use it, for example,
to add up a plan whose every property is a number.
What TypeScript knows about the names
Paste details.ts into a new file in VS Code (Visual Studio Code,
your editor) and hover over key: it says string, any text at all,
not "one of id, title and due". That looks like TypeScript
forgetting what it knows, but it is the only honest answer.
TypeScript checks your code once, before the program runs, and that
one check has to hold for every value that could arrive. A function
that takes a Task also takes a PlannedTask, which adds minutes:
lesson 6.4's "bigger fits smaller". A box typed Task can hold a
PlannedTask just as well. So TypeScript cannot know which names the
object will have. Object.keys, though, runs in Node, on the object
that actually arrives, and lists every name that object has. Here a
planned milk, due Friday and taking 5 minutes, goes into a function
that takes a Task:
planned.ts
function names(task: Task) { return Object.keys(task);}
string[]
What TypeScript sees
Does: Checks names before the run, for any value that fits Task
Never: It never knows which object will come in
names(milk)
idtitledueminutes
Not in Task, yet listed
What Node finds
Does: Reads the object it is given, every name on it
Never: It never looks at Task
TypeScript sees a Task; Node finds every name the object has
It prints [ 'id', 'title', 'due', 'minutes' ]: four names, from a
function that only ever heard of three.
The values are vaguer still. Hover over value in the same
details.ts, and it says any, which lesson 5.1 called TypeScript's
word for "anything at all". For an object whose type is an interface
(the way this course writes object outlines, lesson 6.5), TypeScript
does not say what the values from Object.entries hold. An interface
can be given more properties later, by a second interface of the
same name (lesson 6.5's merging), so TypeScript will not promise what
kind each value is: it calls them any, and checks nothing you do
with them.
This is the second price of interface that lesson 6.5 promised.
Written as type Task = { … }, the same loop gives value the type
string | number, a string or a number, and TypeScript refuses the
Bad version below before it runs, with Property 'toUpperCase' does not exist on type 'string | number'. The course still writes outlines
with interface; in the next lesson, Record gives the values a
type.
Bad — treats every value as text.
TypeScript lets it through; Node stops at the first value that is
not.
The first stops with TypeError: value.toUpperCase is not a function
on id, whose value is the number 1, and no line is printed. The
second prints ID: 1, TITLE: Pay rent and DUE: Monday.
TypeScript checks nothing about values from Object.entries, so do
only what works on every value the object can hold: printing always
does. Adding works when every property is a number, as in a plan of
minutes, but TypeScript will not check that for you. When you need a
property's own type, read it by name with a dot:
rent.title.toUpperCase() gives PAY RENT, and TypeScript checks it,
because title is a string.
Predict before you run
This task was written with its properties in another order than
Task lists them. Decide what the last line prints before you run
it.
Square brackets read a property by its name given as text:
rent["title"] is the same as rent.title, the way tasks[0]
reads a list by place. So it seems the names from Object.keys
could read every value, one by one.
Common mistake
Reading each property with a name from Object.keys
You want every property of rent printed, so you loop over its
names and look each value up:
key is a string, any text at all, and Task has no property for
almost every text: "date", "colour", "x". TypeScript cannot say
what rent[key] would hold. With Object.entries, TypeScript's own
description of the method already calls the values any; here nothing
does, and TypeScript would have to guess any itself. That is the
"implicitly has an 'any' type" you met in lesson 5.1: TypeScript will
not guess any on its own, so it refuses the file, and nothing runs.
Its second line, about an index signature, says the same: Task has
no rule for a property whose name is any text.
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Task'. No index signature with a parameter of type 'string' was found on type 'Task'.
The fix
Ask for the values together with the names, so nothing has to be
looked up:
It prints the three lines. When the error is TS7053 (TS for
TypeScript, then the number of the message) inside a loop over
Object.keys, look for type 'string' can't be used to index in its
message. To index here means to look a value up in square brackets:
the name is fine; it is the lookup TypeScript cannot check. Switch to
Object.entries, or to Object.values when the names do not matter.
This program should print Planned: 80 minutes, but TypeScript
refuses it. Change the loop so it adds up every value of plan,
and leave the other lines as they are.
Loading the editor…
Exercise · Write the code
Print every property of a task
Write printDetails, which takes a Task and prints each of its
properties on a line of its own, as id: 1. Use Object.entries,
so it never names a property. The program should then print five
lines: three for rent, two for water.
Loading the editor…
Exercise · Predict the result
A PlannedTask in a Task box
PlannedTask adds minutes: number to Task. What does the last
line print?
Why is a name from Object.keys(task) only a string?
Check yourself
A loop prints each name of rent with rent[key]. What fixes
it?
0 of 0 answered.
A cheat sheet to keep
Cheat sheet
Iterating over objects
What things are
Word
What it means
Object
Comes with the language; its methods work on any object
Entry
A pair: a property's name, then its value
any
Anything at all: TypeScript checks nothing done with it
Code
Write
What you get
Object.keys(rent)
The names: [ 'id', 'title', 'due' ]
Object.values(rent)
The values: [ 1, 'Pay rent', 'Monday' ]
Object.entries(rent)
The pairs: [ 'id', 1 ] first
const [key, value]
In a for...of: each pair taken apart by place
rent["title"]
The same as rent.title
Rules
Rule
What it means
As written
Names come in the order the object was written
Only what is there
A left-out optional property is not listed
Extras too
A bigger object's own names are listed
Names are string
TypeScript cannot know them before the run
Values are any
For an interface: print them, or read by name
rent[key]
TS7053: use Object.entries instead
Where to go next
You can now go through every property of an object without naming
one: its names with Object.keys, its values with
Object.values, and both together with Object.entries, taken
apart by place in a loop. You also know why TypeScript calls each
name a string, and why a name from Object.keys cannot look a
value up.
Next is Dictionaries and collections: Record, Map, and Set.
There the names themselves are what you keep, such as the days of a
week, and Record says what every value holds, so the values you take
out are checked again.
Before you move on, write an object of your own: your morning in
minutes, with a property for each part of it. Print it with the
Object.entries loop, then add one more property and run it again
without touching the loop. One more line should appear.