// 1. 페이지의 에서 최대한 위에 이 코드를 붙여넣으세요. // 아래의 메타 태그를 복사해 사이트 홈페이지의 섹션에 붙여 넣어주세요. //2. 여는 태그 바로 뒤에 코드를 붙여넣으세요.

새소식

반응형
Javascript/문법

자바스크립트 오브젝트 안에 특정 키가 있는지 확인

  • -
반응형

자바스크립트에서 객체(Object) 안에 특정 키(key)가 있는지 확인하는 방법은 다양합니다.

 

hasOwnProperty 메서드 사용하기:

const myObject = {
  key1: 'value1',
  key2: 'value2'
};

if (myObject.hasOwnProperty('key1')) {
  console.log('key1 exists in the object.');
} else {
  console.log('key1 does not exist in the object.');
}

 

in 연산자 사용하기:

const myObject = {
  key1: 'value1',
  key2: 'value2'
};

if ('key1' in myObject) {
  console.log('key1 exists in the object.');
} else {
  console.log('key1 does not exist in the object.');
}

 

undefined 체크하기:

const myObject = {
  key1: 'value1',
  key2: 'value2'
};

if (myObject['key1'] !== undefined) {
  console.log('key1 exists in the object.');
} else {
  console.log('key1 does not exist in the object.');
}

 

ES6의 Object.keys 사용하기:

const myObject = {
  key1: 'value1',
  key2: 'value2'
};

const keys = Object.keys(myObject);
if (keys.includes('key1')) {
  console.log('key1 exists in the object.');
} else {
  console.log('key1 does not exist in the object.');
}

 

ES6의 Object.getOwnPropertyNames 사용하기:

const myObject = {
  key1: 'value1',
  key2: 'value2'
};

const propertyNames = Object.getOwnPropertyNames(myObject);
if (propertyNames.includes('key1')) {
  console.log('key1 exists in the object.');
} else {
  console.log('key1 does not exist in the object.');
}
반응형
Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.