객체 속성 순환 (Looping through Object Properties)

In JavaScript, objects store data in the form of key-value pairs. Object properties can be accessed and manipulated using various methods. One common task is looping through object properties to perform operations on each property.

1. for…in loop

The most straightforward method to loop through object properties is by using a for...in loop. This loop iterates over all enumerable properties of an object. Here’s an example:

const car = {
  brand: 'Tesla',
  model: 'Model 3',
  color: 'red',
  year: 2021
};

for (let key in car) {
  console.log(key + ': ' + car[key]);
}

Output:

brand: Tesla
model: Model 3
color: red
year: 2021

2. Object.keys()

If you only need to access the keys of an object, you can use the Object.keys() method. This method returns an array of the object’s own enumerable property names. Here’s an example:

const computer = {
  brand: 'Apple',
  model: 'MacBook Pro',
  color: 'silver',
  year: 2020
};

const keys = Object.keys(computer);
console.log(keys);

Output:

[ 'brand', 'model', 'color', 'year' ]

3. Object.values()

To access the values of an object’s properties, you can use the Object.values() method. This method returns an array of the object’s own enumerable property values. Here’s an example:

const person = {
  name: 'John',
  age: 28,
  occupation: 'developer',
  country: 'USA'
};

const values = Object.values(person);
console.log(values);

Output:

[ 'John', 28, 'developer', 'USA' ]

4. Object.entries()

If you need to access both the keys and values of an object’s properties simultaneously, you can use the Object.entries() method. This method returns an array of the object’s own enumerable property as [key, value] pairs. Here’s an example:

const fruit = {
  name: 'apple',
  color: 'red',
  shape: 'round'
};

const entries = Object.entries(fruit);
console.log(entries);

Output:

[
  [ 'name', 'apple' ],
  [ 'color', 'red' ],
  [ 'shape', 'round' ]
]

By using these methods, you can easily loop through and access the properties of JavaScript objects. Utilize the appropriate method based on your specific needs and requirements.

Remember, when iterating over objects, the order of the properties is not guaranteed.