TypeScript Array Object.values() Method
Object.values() is a functionality in TypeScript that returns an array extracting the values of an object. The order of elements is the same as they are in the object. It returns an array of an object's enumerable property values.
Syntax:
Object.values(object);
Parameters:
- object: Here you have to pass the object whose values you want to extract.
Return Value:
An array that contains the property values of the given object which are enumerable and have string keys.
NOTE: Since Object.values() is not directly available in TypeScript, we will implement it using the interface class.
Example 1: Basic Implementation
The below code example is the bais implementation of object.values() method in TypeScript.
interface Geek {
name: string;
workForce: number;
}
const geek: Geek = {
name: "GeeksforGeeks",
workForce: 200
};
const valArray: (number | string)[] =
Object.values(geek)
console.log(valArray);
Output:
["GeeksforGeeks", 200]
Example 2: Implementation with Different Data Types
In this example we defines an interface Car and two car objects car1 and car2. It then uses Object.values() to extract and log the values of these objects as arrays, showing their properties.
interface Car {
carName: string;
carNumber: string;
model: number,
sportsCar: boolean
}
const car1: Car = {
carName: "Alto",
carNumber: "AB05XXXX",
model: 2023,
sportsCar: false
};
const car2: Car = {
carName: "F1",
carNumber: "AB05X0X0",
model: 2024,
sportsCar: true
};
const carArr1 = Object.values(car1);
const carArr2 = Object.values(car2);
console.log(carArr1);
console.log(carArr2);
Output:
["Alto", "AB05XXXX", 2023, false]
["F1", "AB05X0X0", 2024, true]