Open In App

TypeScript Array entries() Method

TypeScript entries() method of Array instances returns a new array iterator object that contains the key/value pairs for each index in the array. This method is useful when you need to iterate over the key/value pairs in the array.

Note: In TypeScript, the entries() method is not available directly on arrays as it is in JavaScript for objects, but we can achieve a similar result through a different approach.



Syntax:

Object.entries(arrayName)

Return Value:

An iterator that yields key-value pairs, where keys are indices and values are array elements.

Example 1: We will access student names and indices using entries().






const students: string[] =
    ["Pankaj", "Ram", "Shravan"];
const studentIterator =
    Object.entries(students);
 
// Using a for-of loop to
// access each key-value pair
for (const [index, value] of studentIterator) {
    console.log(`Index: ${index}, Value: ${value}`);
}

Output:

Index: 0, Value: Pankaj
Index: 1, Value: Ram
Index: 2, Value: Shravan

Example 2: We will access number array elements with indices using a while loop.




const numbers: number[] = [10, 20, 30];
const numberIterator = Object.entries(numbers);
 
// we will use for loop to
// access key-value pair
for (const [index, value] of numberIterator) {
    console.log(`Index: ${index}, Value: ${value}`);
}

Output:

Index: 0, Value: 10
Index: 1, Value: 20
Index: 2, Value: 30

Supported Browsers:

Article Tags :