Last updated: Feb 27, 2024
Reading timeยท2 min
To iterate over an object:
Object.keys()
method to get an array of the object's keys.Array.forEach()
method to iterate over the array.const obj = { name: 'Bobby Hadz', country: 'Chile', }; (Object.keys(obj) as (keyof typeof obj)[]).forEach((key, index) => { // ๐๏ธ name Bobby Hadz 0, country Chile 1 console.log(key, obj[key], index); });
The Object.keys() method returns an array of the object's keys.
const obj = { name: 'Bobby Hadz', country: 'Chile', }; // ๐๏ธ [ 'name', 'country' ] console.log(Object.keys(obj));
We used keyof typeof to
set the type of Object.keys()
to an array containing keys of obj
, so we can
safely access its values.
The function we passed to the Array.forEach method gets called with each element in the array.
The function also gets passed the index of the current iteration as shown in the examples.
This is a two-step process:
Object.entries()
method to get an array of key-value pairs.forEach()
method to iterate over the array.const obj = { name: 'Bobby Hadz', country: 'Chile', }; Object.entries(obj).forEach(([key, value], index) => { // name Bobby Hadz 0 // country Chile 1 console.log(key, value, index); });
The Object.entries() method returns an array of the given object's key-value pairs.
const obj = { name: 'Bobby Hadz', country: 'Chile', }; // ๐๏ธ const result: [string, string][] const result = Object.entries(obj); // ๐๏ธ [['name', 'Bobby Hadz'], ['country', 'Chile']] console.log(result);
The forEach()
method gets passed an array containing 2
elements on each
iteration - the key and the value.
We can use destructuring to get the key and value directly.
const obj = { name: 'Bobby Hadz', country: 'Chile', }; Object.entries(obj).forEach(([key, value], index) => { // name Bobby Hadz 0 // country Chile 1 console.log(key, value, index); });
We used destructuring assignment in the function's parameter list.
This is very similar to the following line of code.
const [key, value] = ['name', 'Bobby Hadz']; console.log(key); // ๐๏ธ "name" console.log(value); // ๐๏ธ "Bobby Hadz"
We are basically assigning the array elements to variables (the order is preserved).
You can also use the Object.values()
method if you need to iterate directly
over the object's values.
const obj = { name: 'Bobby Hadz', country: 'Chile', }; Object.values(obj).forEach((value, index) => { // Bobby Hadz 0 // Chile 1 console.log(value, index); });
The Object.values() method returns an array of the object's values.
const obj = { name: 'Bobby Hadz', country: 'Chile', }; const values = Object.values(obj); // ๐๏ธ [ 'Bobby Hadz', 'Chile' ] console.log(values);
This is useful when you don't need to access the key of the current iteration.