TypeScript Array Object.entries() Method
Last Updated :
15 Jul, 2024
Improve
The Object.entries() method in TypeScript is used for creating an array of key-value pairs from an object's keys and values. This method simplifies the process of iterating over an object's properties and enables easier data manipulation.
Syntax
Object.entries(obj);
Parameter
- obj: It takes the object as a parameter whose key-value pair you want to store in the array.
Return Value
- The method returns an array of arrays. Each nested array contains a key and a value pair from the object.
Example of TypeScript Array Object.entries() Method
Example 1: In this example, we are going to create key-value pairs from the given person object.
interface Company {
name: string;
workForce: number;
}
const person: Company = {
name: "GeeksforGeeks",
workForce: 200,
};
const personEntries = Object.entries(person);
console.log(personEntries);
Output:
[
["name", "GeeksforGeeks"],
["workForce", 200]
]
Example 2: In this example we are going to extract key-value pairs from the given product list.
interface Product {
id: number;
name: string;
price: number;
}
const products: Product[] = [
{ id: 1, name: "Apple", price: 1.99 },
{ id: 2, name: "Banana", price: 0.79 },
{ id: 3, name: "Orange", price: 1.25 },
];
const productEntries = Object.entries(products);
console.log(productEntries);
Output:
[
[ '0', { id: 1, name: 'Apple', price: 1.99 } ],
[ '1', { id: 2, name: 'Banana', price: 0.79 } ],
[ '2', { id: 3, name: 'Orange', price: 1.25 } ]
]