[자바스크립트] Object null 값? 빈 객체 확인하기
[자바스크립트] Object 빈값? empty Object 확인하기
자바스크립트 객체가 비어있는지 확인하고자 할 때!
일반적인 null 값 체크로는 애매하다.
그럼 어떻게 할까?
1) Object.keys() 를 사용
[예시]
var obj = {};
if(Object.keys(obj).length == 0 && obj.constructor === Object) {
//type your code
}
Object.keys() 로 변환해서 length 를 체크하는 건 알겠는데,
왜 constructor 체크를 할까?
constructor 체크를 안한다면 어떻게 될까?
function constructorCheck(val) {
// return Object.keys(val).length == 0 && val.constructor === Object;
return Object.keys(val).length == 0;
}
// 모든 결과값이 다 true??
constructorCheck(new Object()); // true
constructorCheck(new String()); // true
constructorCheck(new Number()); // true
constructorCheck(new Array()); // true
constructorCheck(new RegExp()); // true
constructorCheck(new Date()); // true
constructorCheck(new Function()); // true
Object 가 비어있는지 확인하려했는데,
난데없이 String, Number, Date... 이런 것들이 와버리면 정확한 체크가 불가능하다.
그래서 constructor 체크로 Object 만을 골라내는 것!
2) JSON 메소드를 사용
[예시]
var obj = {};
if(JSON.parse(obj) == '[object Object]' && JSON.stringify(obj) == '{}') {
//type your code
}
대충 알겠는데, [object Object] 는 뭘까?
왜 [object] 이렇게 나타내지 않고 2번이나 쓸까?
자바스크립트에는 여러타입의 객체가 존재하기 때문에!
//function
JSON.stringify(function(){}) //[object Function]
//Array
JSON.stringify([]) //[object Array]
//Date
JSON.stringify(new Date) //[object Date]
//regExp
JSON.stringify(/x/) //[object RegExp]
//Object
JSON.stringify({}) //[object Object]
Object.keys() 가 궁금하다면?
https://devinserengeti.tistory.com/26?category=901017
[자바스크립트] javascript Object.keys() 사용하기
[자바스크립트] javascript Object.keys() 사용하기 자바스크립트 객체를 배열로 변환해주는 메소드! 객체의 key 로만 이루어진 배열을 반환한다. [사용법] var son = { name : 'Son', age : 30, position : 'forw..
devinserengeti.tistory.com