How to check if an object is empty
Short answer
Object.keys() returns an array of keys. An empty object has none:
const filters = {};
console.log(Object.keys(filters).length === 0);Output:
truenull and undefined
Object.keys(null) throws an error. If the value may be missing, check that first:
const isEmpty = (value) => value == null || Object.keys(value).length === 0;
console.log(isEmpty({}));
console.log(isEmpty(null));
console.log(isEmpty({ page: 1 }));Output:
true
true
falseCommon mistake
An empty object is truthy, so if (obj) does not detect emptiness. Comparing with {} does not work either:
const filters = {};
console.log(filters ? 'has filters' : 'empty');
console.log(filters === {});Output:
has filters
falseFunctions used in this recipe
- Object.keys — Returns an array of an object's property names.