본문 바로가기

Search/Javascript

json에서 key 값이 존재 하는지 확인

const object_1 = { test_1:'test 1' }

console.log( object_1.hasOwnProperty('test_1') ) // true

console.log( object_1.hasOwnProperty('test_2') ) // false

const object_2 = { test_1:'test 1', test_2:undefined }

console.log( object_2.hasOwnProperty('test_1') ) // true

console.log( object_2.hasOwnProperty('test_2') ) // true

ㅇ key in Object

최근 자바스크립트 기본을 다시 다지기 위해 읽는 사이트에 예제가 있었다.
기본도 못하고 있다는 생각이 들어버렸다.. 방법은 간단했다.

 

const object_1 = { test_1:'test 1' }

console.log( 'test_1' in object_1 ) // true

console.log( 'test_2' in object_1 ) // false

물론 다음의 경우도 커버 가능하다.

const object_2 = { test_1:'test 1', test_2:undefined }

console.log( 'test_1' in object_2 ) // true

console.log( 'test_2' in object_2 ) // true

 

이 방법엔 단점이 있다.
다음에서 처럼 Object의 프로토타입 체인으로 생성한 프로퍼티도 체크한다는 것이다.

const object_3 = { test_1:'test 1' }

Object.prototype.test_2 = undefined

console.log( 'test_1' in object_3 ) // true

console.log( 'test_2' in object_3 ) // true

ㅇ Object.hasOwnProperty

해당 메소드는 객체가 특정 프로퍼티를 소유했는지를 반환한다. 특히 객체가 지정된 속성을 프로토타입 체인을 통해 상속되지 않은 그 객체의 직접 속성으로 포함하는지를 나타내는 boolean을 반환한다.
해당 메소드는 MDN doc과 여기에 잘 설명 해놓았다.

 

해당 메소드를 사용하면

 

위 두 경우 모두 커버가 가능 할 뿐 아니라

 

const object_3 = { test_1:'test 1' }

Object.prototype.test_2 = undefined

console.log( object_3.hasOwnProperty('test_1') ) // true

console.log( object_3.hasOwnProperty('test_2') ) // false

 

해당 객체의 직접적인 속성만을 검사 할 수 있다.

'Search > Javascript' 카테고리의 다른 글

https://ko.javascript.info/  (0) 2021.03.17