자바스크립트에서 객체(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.');
}