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.
SyntaxObject.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() MethodExample 1: In this example, we are going to create key-value pairs from the given person object.
TypeScript
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.
TypeScript
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 } ]
] FAQs – TypeScript Array Object.entries() MethodWhat does the Object.entries() method do?The Object.entries() method creates an array of key-value pairs from the keys and values of the object passed to it as a parameter. Each key-value pair is represented as an array, with the key as the first element and the value as the second element.
Can Object.entries() handle arrays?Yes, Object.entries() can handle arrays. When used on an array, it returns an array of key-value pairs where the keys are the indices of the array elements and the values are the elements themselves.
Is Object.entries() affected by the order of properties in the object?Yes, Object.entries() respects the order of the properties as they are defined in the object. The key-value pairs in the resulting array will be in the same order as the properties in the object.
Does Object.entries() work on objects with symbolic keys?No, Object.entries() does not include properties with symbolic keys. It only includes properties with string keys.
How does Object.entries() handle non-enumerable properties?Object.entries() only includes enumerable properties in the resulting array. Non-enumerable properties are not included in the key-value pairs generated by this method.
|