includes() 사용
const obj = {a: false, b: true, c: null};
Object.keys(obj).includes('a');
// true
Object.keys(obj).includes('abc');
// false
Object.keys() 메서드로 객체의 모든 키값을 담은 배열을 생성해 주고, includes() 메서드로 해당 키가 존재하는지 판별해 줍니다.
in 연산자 사용
const obj = {a: false, b: true, c: null};
'c' in obj
// true
'abc' in obj
// false
in 연산자를 사용하면 간단한 코드로 key가 존재하는지 간단하게 확인할 수 있습니다.
obj.prototype.test = false;
'test' in obj
// true
다만, 프로퍼티도 같이 체크해 버린다는 문제점이 존재합니다. 해결을 위해서는 includes() 방법 또는 아래 방법을 사용해야 합니다.
hasOwnProperty 메서드 사용
const obj = {a: false, b: true, c: null};
obj.hasOwnProperty('a');
// true
obj.hasOwnProperty('abc');
// false
hasOwnProperty 메서드는 스스로 정의한 프로퍼티에 한해서 특정 키의 소유 여부를 반환해 줍니다.
obj.prototype.test = true;
obj.hasOwnProperty('test');
// false
해당 메서드를 사용하면 직접적인 속성만을 검사할 수 있기에 in 연산자에서 발생한 프로퍼티도 체크하는 문제도 해결 가능합니다.
참고자료
https://stackoverflow.com/questions/455338/how-do-i-check-if-an-object-has-a-key-in-javascript
How do I check if an object has a key in JavaScript?
Which is the right thing to do? if (myObj['key'] == undefined) or if (myObj['key'] == null) or if (myObj['key'])
stackoverflow.com
https://www.freecodecamp.org/news/how-to-check-if-an-object-has-a-key-in-javascript/
JavaScript Key in Object – How to Check if an Object has a Key in JS
Objects in JavaScript are non-primitive data types that hold an unordered collection of key-value pairs. As you can see in the image above, the key is the property, and each object value must have a key. When interacting with objects, situations might aris
www.freecodecamp.org