In JavaScript, an object is an unordered collection of key-value pairs. Properties are the values associated with a specific key in an object. In this blog post, we will explore 5 different examples of getting properties of objects in JavaScript.
This method returns an array of all the enumerable properties of an object.
Example:
const car = {
make: "Toyota",
model: "Camry",
year: 2022
};
console.log(Object.keys(car)); // Output: ["make", "model", "year"]
This method returns an array of all the values of the enumerable properties of an object.
Example:
const car = {
make: "Toyota",
model: "Camry",
year: 2022
};
console.log(Object.values(car)); // Output: ["Toyota", "Camry", 2022]
This method returns an array of arrays containing the key-value pairs of the enumerable properties of an object.
Example:
const car = {
make: "Toyota",
model: "Camry",
year: 2022
};
console.log(Object.entries(car)); // Output: [["make", "Toyota"], ["model", "Camry"], ["year", 2022]]
The for…in loop allows you to iterate over the enumerable properties of an object.
Example:
const car = {
make: "Toyota",
model: "Camry",
year: 2022
};
for (const key in car) {
console.log(`${key}: ${car[key]}`);
}
/* Output:
make: Toyota
model: Camry
year: 2022
*/
This method returns an array of all the properties (enumerable or not) of an object.
Example:
const car = {
make: "Toyota",
model: "Camry",
year: 2022
};
console.log(Object.getOwnPropertyNames(car)); // Output: ["make", "model", "year"]
These are only a few examples of how to obtain object properties in JavaScript. You can better manipulate objects in your code by understanding these methods and strategies.
Leave a Reply