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?
The Java Map interface has a special method for checking if a Map is empty. This method is called isEmpty() and it returns either true or false . The isEmpty() method will return false if the Map instance contains 1 or more entries. If the Map contains 0 entries, isEmpty() will return true .
C++ map empty() function is used to check whether the map container is empty or not. It returns true, if the map container is empty (size is 0) otherwise false.
The Map.has() method in JavaScript is used to check whether an element with a specified key exists in a map or not. It returns a boolean value indicating the presence or absence of an element with a specified key in a map.
To check if an object is empty in TypeScript:Use the Object. keys() method to get an array of the object's keys. Access the length property on the array. If the length property is equal to 0 , the object is empty.
You use its size
property. Both Maps and Sets have it (here and here).
const populatedSet = new Set(['foo']);
console.log(populatedSet.size); // 1
const populatedMap = new Map([['foo', 1]]);
console.log(populatedMap.size); // 1
(Side note: WeakMaps and WeakSets don't have size
or several other features their "strong" counterparts have, in order to keep their implementations, and code using them, sane. :-) Where they have similar functionality, they offer the same API, but they aren't subclasses.)
You can do this directly
if(storeMapDetails.size == 0){
//Do something
}
You can check this directly
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With