How to use Object.getOwnPropertyNames In Typescript
In this approach we are using `Object.getOwnPropertyNames()` to retrieve an array containing all property names of an object. It includes non-enumerable properties and returns them as an array for further processing or analysis.
Syntax:
Object.getOwnPropertyNames(obj); // Returns an array of all properties' names
Example: In this example we creates a dictionary object and retrieves all property names using Object.getOwnPropertyNames(), storing them in an array. It then logs the array of property names.
// Creating a dictionary object
const dictionary = {
name: "Nikunj",
email: "gfg@gmail.com",
isActive: true,
mobile: 9876543210,
}
// Fetch all property names from the dictionary as an array
const allProperties = Object.getOwnPropertyNames(dictionary);
console.log("Here, We have an array of all property names:");
console.log(allProperties);
Output:
"Here, We have an array of all property names:"
["name", "email", "isActive", "mobile"]
How to Convert a Dictionary to an Array in TypeScript ?
In TypeScript, converting a dictionary(an object) into an Array can be useful in scenarios where you need to work with the values in a more iterable and flexible manner.
These are the following approaches:
Table of Content
- Using Object.keys method
- Using Object.values method
- Using Object.entries method
- Using Object.getOwnPropertyNames
Contact Us