10월, 2015의 게시물 표시

Underscore.js로 Object에 특정 Key 존재여부 체크하기

최근 회사 프로젝트를 진행하면서 Object의 특정 Key가 존재하는지 체크할 일이 생겼는데 여러가지 방법을 시도해보았으나 제일 좋은것은 Underscore.js의 has 메서드인 것 같다. 아래는 Underscore.js의 document의 has 메서드 부분이다. has _.has(object, key) Does the object contain the given key? Identical to  object.hasOwnProperty(key) , but uses a safe reference to the  hasOwnProperty  function, in case it's been  overridden accidentally . _.has({a: 1, b: 2, c: 3}, "b"); => true 여기서처럼 Object에 특정 Key가 존재하는지 체크할 때는 _.has 를 이용하는 것이 깔끔한 것 같다. 추가로 Object의 hasOwnProperty 메서드를 사용해도 되지 않냐고 생각할 수도 있지만 overridden accidentally 링크에서 설명하는 것처럼 prototype의 키 값이 충돌하는 경우 문제가 될 수 있기 때문에 _.has 를 사용하는 것이 더 나은 선택으로 보인다.