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 article, we will explore 5 different examples of how to access object properties in JavaScript.
1. Method Object.keys()
This method returns an array of all enumerable properties of an object.
Example:
const car = {
brand: "Toyota" ,
model: "Camry" ,
year: 2022
};
console. log (Object.keys(car)); // Output: [ "make" , "model" , "year" ]
2. Method Object.values()
This method returns an array of all the values of an object’s enumerable properties.
Example:
const car = {
brand: "Toyota" ,
model: "Camry" ,
year : 2022
};
console. log (Object.values(car)); // Output: ["Toyota", "Camry", 2022]
3. Method Object.entries()
This method returns an array of arrays containing the key-value pairs of the enumerable properties of an object.
Example:
const car = {
brand: "Toyota" ,
model: "Camry" ,
year: 2022
};
console.log( Object .entries(car)); // Output : [[ "make" , "Toyota" ], [ "model" , "Camry" ], [ "year" , 2022 ]]
4. Loop for…in
The for…in loop allows you to iterate over the enumerable properties of an object.
Example:
const car = {
brand: "Toyota" ,
model: "Camry" ,
year : 2022
};
for ( const key in car) {
console. log (` ${key} : ${car [key]}`);
}
/* Exit:
Brand: Toyota
Model: Camry
year: 2022
*/
5. Method Object.getOwnPropertyNames()
This method returns an array of all properties (enumerable or not) of an object.
Example:
const car = {
brand: "Toyota" ,
model: "Camry" ,
year: 2022
};
console. log (Object.getOwnPropertyNames(car)); // Output: [ "make" , "model" , "year" ]
In conclusion, these are just a few examples of how to access object properties in JavaScript. Understanding these methods is essential for programmers who want to work with objects in JavaScript. Also, it is important to note that some properties may not be enumerable, which means that they will not appear in the output of methods like
In summary, these are just a few of the many methods and techniques available for accessing properties on JavaScript objects. It’s important that you practice and experiment with different approaches to find out which one works best for your project. The more you practice, the more comfortable you’ll become with manipulating objects in JavaScript.
Deixe um comentário