[javascript] 객체의 속성 값 검사하기

자바스크립트에서 객체의 속성 값을 검사하는 방법에 대해 알아보겠습니다.

솔루션

자바스크립트에서 객체의 속성 값을 검사하는 가장 간단한 방법은 undefined 값을 확인하는 것입니다.

예를 들어, 다음과 같은 객체가 있다고 가정해봅시다.

const person = {
  name: 'John',
  age: 30,
  address: {
    city: 'Seoul',
    street: 'Gangnam-gu',
  },
};
  1. 단일 속성 값 확인
    if (person.name !== undefined) {
      console.log('name 속성이 존재합니다');
    }
    
  2. 중첩 속성 값 확인
    if (person.address !== undefined && person.address.city !== undefined) {
      console.log('address 속성과 city 속성이 모두 존재합니다');
    }
    
  3. Optional chaining 사용
    if (person?.address?.city !== undefined) {
      console.log('address 속성과 city 속성이 모두 존재합니다');
    }
    

위의 예제에서는 undefined 값을 확인하는 방법을 보여주었습니다. 단일 속성의 경우는 간단히 obj.property !== undefined로 확인할 수 있습니다. 중첩 속성의 경우에는 obj.property1 !== undefined && obj.property1.property2 !== undefined와 같이 확인할 수 있습니다.

참고 자료