728x90
JavaScript에서 객체(Object)는 데이터를 key-value 쌍으로 저장하는 강력한 자료 구조입니다. 객체를 효과적으로 다루기 위해 다양한 함수와 연산자가 제공되며, 이 글에서는 이를 키워드와 함께 자세히 설명합니다. 초보자부터 중급 개발자까지 유용하게 참고할 수 있도록 예제와 함께 정리했습니다.
1. 객체 속성 접근 및 열거
-
Object.keys(obj): 객체의 열거 가능한 속성 이름(key)을 배열로 반환합니다.
const obj = { a: 1, b: 2, c: 3 }; console.log(Object.keys(obj)); // ['a', 'b', 'c']
-
열거 불가능한 속성(예: enumerable: false)은 제외됩니다.
-
-
Object.values(obj): 객체의 열거 가능한 속성 값(value)을 배열로 반환합니다.
console.log(Object.values(obj)); // [1, 2, 3]
-
Object.entries(obj): 객체의 열거 가능한 속성을 [key, value] 쌍의 배열로 반환합니다.
console.log(Object.entries(obj)); // [['a', 1], ['b', 2], ['c', 3]]
-
for...of 루프와 함께 사용하면 속성을 쉽게 순회할 수 있습니다.
-
728x90
-
for...in 루프: 객체의 열거 가능한 속성을 순회합니다.
for (let key in obj) { console.log(`${key}: ${obj[key]}`); } // 출력: // a: 1 // b: 2 // c: 3
-
프로토타입 체인까지 순회하므로 hasOwnProperty로 필터링하는 것이 좋습니다.
-
2. 객체 속성 확인
-
in 연산자: 객체에 특정 속성이 있는지 확인합니다(프로토타입 체인 포함).
console.log('a' in obj); // true console.log('toString' in obj); // true (프로토타입에서 상속됨)
-
hasOwnProperty(prop): 객체가 특정 속성을 직접 소유하고 있는지 확인합니다(프로토타입 제외).
console.log(obj.hasOwnProperty('a')); // true console.log(obj.hasOwnProperty('toString')); // false
-
propertyIsEnumerable(prop): 속성이 열거 가능(enumarable)인지 확인합니다.
console.log(obj.propertyIsEnumerable('a')); // true
3. 객체 복사 및 병합
-
Object.assign(target, ...sources): 하나 이상의 소스 객체를 대상 객체로 복사합니다(얕은 복사).
const target = { a: 1 }; const source = { b: 2, c: 3 }; Object.assign(target, source); console.log(target); // { a: 1, b: 2, c: 3 }
-
중첩 객체는 참조만 복사되므로 깊은 복사가 필요하면 별도 처리가 필요합니다.
-
-
spread 연산자 (...obj): 객체를 펼쳐 새로운 객체를 생성합니다(얕은 복사).
const newObj = { ...obj, d: 4 }; console.log(newObj); // { a: 1, b: 2, c: 3, d: 4 }
4. 객체 생성 및 프로토타입 관리
-
Object.create(proto): 지정한 프로토타입 객체를 기반으로 새 객체를 생성합니다.
const proto = { greet: () => 'Hello' }; const obj2 = Object.create(proto); console.log(obj2.greet()); // 'Hello'
-
Object.getPrototypeOf(obj): 객체의 프로토타입을 반환합니다.
console.log(Object.getPrototypeOf(obj2) === proto); // true
-
Object.setPrototypeOf(obj, proto): 객체의 프로토타입을 설정합니다.
const obj3 = {}; Object.setPrototypeOf(obj3, proto); console.log(obj3.greet()); // 'Hello'
5. 속성 정의 및 관리
-
Object.defineProperty(obj, prop, descriptor): 객체에 새 속성을 정의하거나 기존 속성을 수정합니다.
const obj4 = {}; Object.defineProperty(obj4, 'key', { value: 42, writable: false, // 수정 불가 enumerable: true, // 열거 가능 configurable: true // 재정의 가능 }); console.log(obj4.key); // 42 obj4.key = 100; // writable: false라 무시됨 console.log(obj4.key); // 42
-
Object.defineProperties(obj, props): 여러 속성을 한 번에 정의합니다.
const obj5 = {}; Object.defineProperties(obj5, { a: { value: 1, writable: true }, b: { value: 2, enumerable: true } });
-
Object.getOwnPropertyDescriptor(obj, prop): 속성의 디스크립터를 반환합니다.
console.log(Object.getOwnPropertyDescriptor(obj4, 'key')); // { value: 42, writable: false, enumerable: true, configurable: true }
-
Object.getOwnPropertyDescriptors(obj): 모든 속성의 디스크립터를 반환합니다.
console.log(Object.getOwnPropertyDescriptors(obj5));
6. 객체 변경 방지
-
Object.freeze(obj): 객체를 동결하여 속성 추가, 삭제, 수정을 막습니다.
const frozen = { x: 1 }; Object.freeze(frozen); frozen.x = 2; // 무시됨 console.log(frozen.x); // 1
-
Object.seal(obj): 객체를 봉인하여 속성 추가/삭제를 막지만 값 수정은 가능합니다.
const sealed = { y: 2 }; Object.seal(sealed); sealed.y = 3; // 가능 console.log(sealed.y); // 3 delete sealed.y; // 불가능
-
Object.preventExtensions(obj): 속성 추가만 막습니다.
const ext = { z: 3 }; Object.preventExtensions(ext); ext.w = 4; // 무시됨
-
Object.isFrozen(obj): 객체가 동결되었는지 확인합니다.
console.log(Object.isFrozen(frozen)); // true
-
Object.isSealed(obj): 객체가 봉인되었는지 확인합니다.
console.log(Object.isSealed(sealed)); // true
-
Object.isExtensible(obj): 객체가 확장 가능(속성 추가 가능)인지 확인합니다.
console.log(Object.isExtensible(ext)); // false
7. 속성 삭제
-
delete 연산자: 객체에서 특정 속성을 삭제합니다.
const obj6 = { a: 1, b: 2 }; delete obj6.a; console.log(obj6); // { b: 2 }
-
프로토타입 속성은 삭제되지 않습니다.
-
마무리
JavaScript 객체를 다루는 다양한 메서드와 연산자는 상황에 따라 유연하게 활용할 수 있습니다. 속성 열거, 복사, 프로토타입 관리, 변경 방지 등 목적에 맞는 도구를 선택해 사용하면 코드의 가독성과 유지보수성이 크게 향상됩니다. 위 예제를 직접 실행해보며 익히는 것을 추천합니다!
728x90
'ec6' 카테고리의 다른 글
자바스크립트 기호의 의미와 용도 (1) | 2025.03.08 |
---|