본문 바로가기
JS

JavaScript 객체의 프로퍼티 접근 및 조작 방법

by 하겐모아 2024. 1. 28.

📢  JavaScript 객체의 프로퍼티 접근 및 조작 방법

자바스크립트에서 객체는 키-값 쌍의 집합이다.  이러한 객체의 프로퍼티는 다양한 방법으로 접근하고 조작할 수 있다. 

 

📌 프로퍼티 검색

객체의 프로퍼티를 검색하는 방법에는 점 표기법(dot notation)과 대괄호 표기법(bracket notation)이 있다.

const person = {
  name: 'Kim',
  age: 30
};

// 점 표기법
console.log(person.name); // 'Kim'

// 대괄호 표기법
console.log(person['age']); // 30

 

대괄호 표기법은 동적으로 프로퍼티 이름을 지정할 수 있기 때문에 유연성이 높다.

const prop = 'name';
console.log(person[prop]); // 'Kim'

 

 

📌 프로퍼티 설정

객체의 프로퍼티를 설정하는 방법도 점 표기법과 대괄호 표기법을 사용할 수 있다.

const person = {
  name: 'John',
  age: 30
};

// 점 표기법
person.name = 'Jane';
console.log(person.name); // 'Jane'

// 대괄호 표기법
person['age'] = 25;
console.log(person['age']); // 25

 

 

📌  프로퍼티 삭제

delete 연산자를 사용하여 객체의 프로퍼티를 삭제할 수 있다.

delete person.age;
console.log(person.age); // undefined

 

 

📌 프로퍼티 존재 여부 테스트

객체의 프로퍼티가 존재하는지 확인하는 방법에는 in 연산자와 hasOwnProperty 메서드가 있다.

const person = {
  name: 'John',
  age: 30
};

// in 연산자
console.log('name' in person); // true
console.log('job' in person); // false

// hasOwnProperty 메서드
console.log(person.hasOwnProperty('age')); // true
console.log(person.hasOwnProperty('job')); // false

 

 

 

📌 프로퍼티 열거

객체의 프로퍼티를 열거하는 방법에는 for...in 루프와 Object.keys 메서드가 있다.

const person = {
  name: 'John',
  age: 30,
  job: 'Developer'
};

// for...in 루프
for (let key in person) {
  if (person.hasOwnProperty(key)) {
    console.log(key + ': ' + person[key]);
  }
}
// Output:
// name: John
// age: 30
// job: Developer

// Object.keys 메서드
Object.keys(person).forEach(key => {
  console.log(key + ': ' + person[key]);
});
// Output:
// name: John
// age: 30
// job: Developer

 

Object.keys는 객체의 열거 가능한 프로퍼티 이름을 배열로 반환한다.

'JS' 카테고리의 다른 글

[React] 아코디언 토글 컴포넌트  (0) 2024.06.25
JavaScript 객체의 확장, 직렬화, 메서드  (0) 2024.01.29
Try-catch 문  (0) 2024.01.25
javascript 기초  (0) 2024.01.23
텍스트 복사 버튼  (0) 2024.01.18