다음과 같은 경우를 객체가 비어있다고 표현하는데, 어떤 객체가 빈 객체인지 체크하는 방법 3가지를 알아보자.
// 객체가 비어있는지 체크하기
let emptyObject = {};
1. Object.keys()
Object.keys() 메서드와 constructor 속성을 함께 사용한다.
Object.keys() 메서드는 주어진 객체 속성의 key들을 문자열 배열 형태로 return한다.
// Object.keys() 예제
const object1 = {
a: 'somestring',
b: 327,
c: false,
};
console.log(Object.keys(object1)); // Array ["a", "b", "c"]
constructor가 필요한 이유는 Object.keys()가 객체가 아닌 배열에게도 적용되기 때문이다. 밑의 코드를 보면 단순 배열의 경우에도 배열의 인덱스가 출력된다. 따라서 타입이 "객체"인 경우만 남겨두기 위해 constructor를 이용해 조건을 추가한다.
// 단순 배열
const arr = ["a", "b", "c"];
console.log(Object.keys(arr)); // console: ['0', '1', '2']
// 배열형 객체
const obj = { 0: "a", 1: "b", 2: "c" };
console.log(Object.keys(obj)); // console: ['0', '1', '2']
// 키와 순서가 무작위인 유사 배열 객체
const anObj = { 100: "a", 2: "b", 7: "c" };
console.log(Object.keys(anObj)); // console: ['2', '7', '100']
다음 코드가 Object.keys()로 객체가 빈 객체인지 확인하는 코드이다.
// 빈 객체인지 확인하는 코드
function isEmptyObj(obj) {
if (obj.constructor === Object && Object.keys(obj).length === 0) {
return true;
}
return false;
}
const obj1 = {};
const obj2 = { message: "안 빔" };
const str = "This_is_string";
console.log(isEmptyObj(obj1)); // true
console.log(isEmptyObj(obj2)); // false
console.log(isEmptyObj(str)); // false
Line 14) obj1은 빈 객체이므로 true가 출력된다.
Line 15) obj2는 빈 객체가 아니므로 false가 출력된다.
Line 16) str은 객체가 아니므로 false가 출력된다.
2. 반복문(for...in)
for...in 반복문과 Object.hasOwnProperty() 메서드를 함께 사용한다. (Object.keys()와 마찬가지 이유로 constructor를 활용한다.)
hasOwnProperty() 메서드를 사용하면 객체에 특정 프로퍼티가 존재하는지 확인할 수 있다. 인수로 전달받은 프로퍼티 키가 객체 고유의 프로퍼티 키인 경우에만 true를 반환하고, 상속받은 프로토타입의 프로퍼티 키인 경우 false를 반환한다.
// hasOwnProperty() 예제
const example = {};
example.hasOwnProperty("prop"); // false
example.prop = "exists";
example.hasOwnProperty("prop"); // true - 'prop' has been defined
example.prop = null;
example.hasOwnProperty("prop"); // true - own property exists with value of null
example.prop = undefined;
example.hasOwnProperty("prop"); // true - own property exists with value of undefined
for...in 반복문에 객체를 넣으면 객체의 key값에 반복해서 접근할 수 있다. 다음 코드가 for...in으로 객체가 빈 객체인지 확인하는 코드이다. 반복문으로 객체의 프로퍼티를 순회하며, key가 하나라도 나오면 false를 return하여 빈 객체가 아니라는 것을 확인할 수 있다.
// 빈 객체인지 확인하는 코드
function isEmptyObj(obj) {
// 객체 타입체크
if (obj.constructor !== Object) {
return false;
}
// property 체크
for (let prop in obj) {
if (obj.hasOwnProperty(prop)) {
return false;
}
}
return true;
}
3. lodash library(_.isEmpty())
lodash의 사용 방법은 아래 링크에 있다.
Lodash
_.defaults({ 'a': 1 }, { 'a': 3, 'b': 2 });_.partition([1, 2, 3, 4], n => n % 2);DownloadLodash is released under the MIT license & supports modern environments. Review the build differences & pick one that’s right for you.InstallationIn
lodash.com
_.isEmpty() 메서드로 값이 비어있는지 아닌지 간단하게 판별할 수 있다.
// 빈 객체인지 확인하는 코드
function isEmptyObj(obj) {
if (obj.constructor === Object && _.isEmpty(obj)) {
return true;
}
return false;
}