[JavaScript] 객체 메서드

ttining·2025년 1월 9일

💡 자바스크립트의 객체 메서드를 알아보자.


Object.keys()

  • 객체의 열거 가능한 속성 이름(key)을 배열로 반환한다.
  • 사용 예시
    const person = { name: "ttining", age: 100 };
    const keys = Object.keys(person);
    console.log(keys); // ["name", "age"]

Object.values()

  • 객체의 열거 가능한 속성 값(value)을 배열로 반환한다.
  • 사용 예시
    const person = { name: "ttining", age: 100 };
    const values = Object.values(person);
    console.log(values); // ["ttining", 100]

Object.entries()

  • 객체의 열거 가능한 속성 [key, value] 쌍을 배열로 반환한다.
  • 사용 예시
    const person = { name: "ttining", age: 100 };
    const entries = Object.entries(person);
    console.log(entries); // [["name", "ttining"], ["age", 100]]

Object.assign()

  • 하나 이상의 객체를 복사하여 새 객체를 반환한다.
  • 속성 값이 동일한 경우, 나중에 복사한 객체가 앞의 객체를 덮어쓴다.
  • 사용 예시
    const person = { name: "ttining", age: 100 };
    const updatedPerson = Object.assign({}, person, { age: 800 });
    console.log(updatedPerson); // { name: "ttining", age: 800 }

Object.freeze()

  • 객체를 동결시켜, 객체의 속성을 변경할 수 없게 만든다.
  • 사용 예시
    const person = { name: "ttining", age: 100 };
    Object.freeze(person);
    person.age = 20; // 변경되지 않음
    console.log(person.age); // 100

Object.getOwnPropertyNames()

  • 객체의 모든 속성 이름을 배열로 반환한다.
  • Object.keys()와 비슷하지만, 상속된 속성은 제외하고 객체 고유의 속성만 반환한다.
  • 사용 예시
    const person = { name: "ttining", age: 100 };
    const propertyNames = Object.getOwnPropertyNames(person);
    console.log(propertyNames); // ["name", "age"]

Object.getOwnPropertyDescriptor()

  • 객체의 특정 속성에 대한 속성 설명자를 반환한다.
  • 사용 예시
    const person = { name: "ttining", age: 100 };
    const descriptor = Object.getOwnPropertyDescriptor(person, "name");
    console.log(descriptor);
    // { value: "ttining", writable: true, enumerable: true, configurable: true }

hasOwnProperty()

  • 객체가 특정 속성을 고유 속성으로 가지고 있는지 확인한다.
  • 사용 예시
    const person = { name: "ttining", age: 100 };
    console.log(person.hasOwnProperty("name")); // true
    console.log(person.hasOwnProperty("address")); // false
profile
내가 보려고 만든 벨로그 *'-'*

0개의 댓글