Monday, June 3, 2024
76
rated 0 times [  78] [ 2]  / answers: 1 / hits: 62790  / 5 Years ago, thu, april 4, 2019, 12:00:00

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?


More From » ecmascript-6

 Answers
0

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.)


[#52302] Friday, March 29, 2019, 5 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kenyonc

Total Points: 235
Total Questions: 106
Total Answers: 125

Location: Bangladesh
Member since Sat, Jan 23, 2021
3 Years ago
;