[JS] 객체 안에 특정 key가 존재하는지 확인하는 방법

양주영·2023년 1월 4일
0

javascript

목록 보기
40/42

한 객체 내에 특정한 key 값을 가졌는지 확인한 후, 값을 각각 다르게 세팅해주어야 했다.
객체에 특정 key가 존재하는지 확인하는 방법은 아래와 같다.

1. Object의 keys를 이용하기

Object.key는 객체의 키를 배열로 리턴한다. 이를 통해 찾는 값이 있는지 확인할 수 있다.

const object1 = {
	test: 'test1'
}
const isExist1 = Object.keys(object1).includes('test')
const isExist2 = Object.keys(object1).includes('test2')

console.log(isExist1); // true
console.log(isExist2); // false
const object2 = {
	test1: 'test1',
  	test2: undefined
}
const isExist3 = Object.keys(object2).includes('test1')
const isExist4 = Object.keys(object2).includes('test2')

console.log(isExist3); // true
console.log(isExist4); // true

2. key in Object

const object1 = {
  test1: 'test1'
}
console.log('test1' in object1); // true
console.log('test2' in object1); // false
const object2 = {
  test1: 'test1',
  test2: undefined
}
console.log('test1' in object2); // true
console.log('test2' in object2); // false

이 방법은 Object의 프로토타입 체인으로 생성한 프로퍼티도 체크한다.

const object3 = {
  test1: 'test1'
}
Object.prototype.test2 = undefined
console.log('test1' in object3); // true
console.log('test2' in object3); // true

3. Object.hasOwnProperty

이 메소드는 객체가 특정 프로퍼티를 소유했는지를 반환한다. 객체가 지정된 속성을 프로토타입 체인을 통해 상속되지 않은 그 객체의 직접 속성으로 포함하는지를 나타내는 boolean을 반환한다.

const object1 = {
	test1: 'test1'
}

console.log(object1.hasOwnProperty('test1')) // true
console.log(object1.hasOwnProperty('test2')) // false

const object2 = {
	test1: 'test1',
  	test2: undefined
}

console.log(object2.hasOwnProperty('test1')) // true
console.log(object2.hasOwnProperty('test2')) // true
const object3 = {
	test1: 'test1'
}
Object.prototype.test2 = undefined
console.log(object3.hasOwnProperty('test1')) // true
console.log(object3.hasOwnProperty('test2')) // false

위의 예제를 보고 해당 객체의 직접적인 속성만을 검사할 수 있다는 것을 확인했다.

  • Object.hasOwnProperty를 왜 쓰는지에 대하여 더 알아보자.
  • 우선

내가 결국 사용했던 코드는 아래와 같다.

Object.prototype.hasOwnProperty.call(params, 'status')

console.log(Object.prototype.hasOwnProperty.call(params, 'status'))Object.prototype.hasOwnProperty.call(params, 'status')


참고
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

profile
뚜벅뚜벅

0개의 댓글