5 Ways to Access Properties in JavaScript Objects

Javascript

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.

  1. Object.keys() method

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"]
  1. Object.values() method

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]
  1. Object.entries() method

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]]
  1. for…in loop

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
*/
  1. Object.getOwnPropertyNames() method

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

Your email address will not be published. Required fields are marked *

0 Comments