With a traditional object in JavaScript, it is easy enough to check if it is empty using the Object.keys
method:
const emptyObj = {};
console.log(Object.keys(emptyObj).length === 0); // true, i.e. empty
const populatedObj = { foo: 'bar' };
console.log(Object.keys(populatedObj).length === 0); // false, not empty
Although a bit redundant, you can use the same approach with arrays too if you like:
const emptyArr = [];
console.log(Object.keys(emptyArr).length === 0); // true
const populatedArr = [1, 2, 3];
console.log(Object.keys(populatedArr).length === 0); // false
However, ES6's handy new data structures Map and Set, don't work the same way. If you try to use Object.keys
on them you will always get an empty array!
const populatedSet = new Set(['foo']);
console.log(Object.keys(populatedSet).length); // 0
const populatedMap = new Map([['foo', 1]]);
console.log(Object.keys(populatedMap).length); // 0
So what is the best way to check whether or not your fancy new ES6 structures are populated? Also, is there some sort of single overloaded method that would work for objects, arrays, Maps, and Sets?