So you have an object, and you don't want to use the for...in
loop to iterate.
Very cool, now you're wondering which function you'd use to iterate over it?
Why not use for...in
for iterating objects?
Well first of all, a little bit of history. In the old days, before ES6, the only way to iterate over an object was to use the for in loop.
1const userMap = {2 id_1: {3 name: 'John Doe',4 },5 id_2: {6 name: 'Jane Doe',7 },8};910for (let id in userMap) {11 const user = userMap[id];12 // Do something with the user13}
Copied!
While this is still a perfectly valid way to iterate over an object, it has it's limitations.
- It will iterate over all the enumerable properties of the object, including the ones that are inherited from the prototype chain.
- We have to use explicitly the
hasOwnProperty
method to check if a property is actually a property of the object itself.
You can read more about in the MDN
article .
A check for the above is simple though, we can use hasOwnProperty
.
1for (let id in userMap) {2 if (userMap.hasOwnProperty(id)) {3 const user = userMap[id];4 // Do something with the user5 }6}
Copied!
But you know, this is 2022, and we can totally avoid those nasty for..in
combined with if
if (pun intended) all that we want is to iterate over an
object's own properties.
For all of the examples below, we will consider the following object (written in TypeScript so we get the shape too).
1type User = {2 name: string;3};45const usersMap: Record<string, User> = {6 id_1: {7 name: 'John Doe',8 },9 id_2: {10 name: 'Jane Doe',11 },12};
Copied!
The key of the object is the ID of the user and the values are the properties of the user (just name in this example).
Iterating over an object's keys
If we want just the keys, we can use Object.keys
.
1const allUserIds = Object.keys(usersMap);23allUserIds.forEach(userId => {4 console.log(userId);5});
Copied!
Iterating over an object's values
If we just want the values, we can use Object.values
.
1const allUsers = Object.values(usersMap);23allUsers.forEach(user => {4 console.log(user);5});
Copied!
Iterating over both object's keys and values
Now what if we want both the keys and the values? We can use Object.entries
.
1const allUsersWithId = Object.entries(usersMap);23allUsersWithId.forEach(([userId, user]) => {4 console.log(userId, user);5});
Copied!
Notice that calling Object.entries
will return an array of tuple.
- The first item in the tuple will be the key of the object.
- The second item will be the value of the object.
This is pretty neat right?
So that was all about some quick tips in JavaScript, Objects and Iterations. See you next time.