TypeScript Array Object.entries() Method
Last Updated :
06 Feb, 2024
The Object.entries() is a method in TypeScript, that is very useful for creating an array of key-value pairs from the keys and values of the object passed to it as a parameter.
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:
It will return an array of arrays where each nested array contains a key and a value pair of objects as values.
Example 1: In this example, we are going to create key-value pairs from the given person object.
Javascript
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.
Javascript
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 } ]
]
Share your thoughts in the comments
Please Login to comment...